我有一个简单的程序,可以读取文件中有多少单词。出于本程序的目的,单词是任何不被空格分隔的单词。我的问题是ifstream正在为我的文件读取字符串字符两次。我不明白这个?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile;
string str1;
string filename;
int count;
cout << "enter a file name: ";
cin >> filename;
while (filename != "quit") {
infile.open(filename.c_str());
if (!infile) {
cout << "Couldn't open file." << endl;
} else {
count = 0;
while (infile) {
infile >> str1;
cout << str1 << endl;
count++;
}
infile.close();
cout << count << endl;
}
cout << "enter a filename: ";
cin >> filename;
}
}
以下是一个示例文件文本:
This &%file should!!,...
have exactly 7 words.
输出:
enter a file name: file1
This
&%file
should!!,...
have
exactly
7
words.
words.
8