c++ - 从 C++ I/O 中的字符串行读取 "tokens"

标签 c++ io tokenize stringstream

我想知道如何在 C++ 中执行以下操作,因为我只熟悉 Java。

我有一个字符串,我们称之为行。 string line = "你好,你好吗";

在 C++ 中,我已从 getLine() 中检索到该行。我想遍历这一行,这样我就可以计算这一行中的单词数。在我的例子中,结果应该是 4。

在 Java 中,我会导入 Scanner。然后做这样的事情:

//Other scanner called fileName over the file
while(fileName.hasNextLine()) {
line = fileName.nextLine();
Scanner sc = new Scanner(line); 
int count=0;
while(sc.hasNext()){
    sc.next();
    count++;
}

我只使用 #include<iostream>, fstream and string.

最佳答案

您可以使用 stringstream

#include <iostream>
#include <sstream> 
#include <string>
using namespace std;

int main() {

    string line;
    getline(cin,line);
    stringstream ss(line);

    string word;

    int count=0;
    while(ss>>word){//ss is used more like cin
        count++;
    }
    cout<<count<<endl;
    return 0;
}

http://ideone.com/Yl25KT

关于c++ - 从 C++ I/O 中的字符串行读取 "tokens",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21145638/

相关文章:

c++ - 指针 : p++ & p+1

c++ - 将图像集成到我的可执行文件中

python - 从Azure blob读取excel数据并使用Python azure函数转换为csv

haskell - Haskell 的 "do"关键字有什么作用?

python - 如何在 NLP 中的 TweetTokenizer 步骤中删除标点符号和数字?

C++:获取 std::vector 的开头地址?

c++ - Pollard Rho 在不太大的输入上崩溃

java - 分割字符串/标记

c - 如何使控制台应用程序接收 100,000 个整数的输入

python - 将 nlp.pipe() 与带有 spaCy 的预分段和预标记化文本一起使用