我想知道如何在 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;
}
关于c++ - 从 C++ I/O 中的字符串行读取 "tokens",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21145638/