我想知道如何在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.
答案 0 :(得分:3)
您可以使用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;
}
答案 1 :(得分:0)
我会避免ifstream::getline
而只是使用ifstream::get
。您甚至不需要使用string
。
#include <iostream>
int main()
{
int numwords = 1; //starts at 1 because there will be (numspaces - 1) words.
char character;
std::ifstream file("readfrom.txt");
if (file.fail())
{
std::cout << "Failed to open file!" << std::endl;
std::cin.get();
return 0;
}
while (!file.eof())
{
file >> character;
if (character == ' ')
{
numwords++;
std::cout << std::endl;
}
else if (character == '\n') //endline code
{
std::cout << "End of line" << std::endl;
break;
}
else
std::cout << character;
}
std::cout << "Line contained " << numwords << " words." << std::endl;
std::cin.get(); //pause
return 0;
}