0
这就是我到目前为止... 这个程序的重点是显示文件中的单词数量,并获取同一文件的单词数量中的字母数量。如何读取文件中的字符数?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int numberOfWords = 0, i = 0;
char letters = 0;
string line;
ifstream myFile;
myFile.open("text.txt");
//I got this to work, it displays the number of words in the file
if (myFile.is_open())
{
while (!myFile.eof())
{
myFile >> line;
i++;
}
numberOfWords = i;
//this is where I'm having trouble. I can't get this code to work for it to display the number of letters in the file.
while (!myFile.eof())
{
//cout << line << endl;
letters = line.length();
letters++;
}
}
myFile.close();
cout << "There are " << numberOfWords << " words in the textfile\n"
<< "There are " << letters << " letters in those " << numberOfWords << " words\n";
cin.get();
return 0;
}
看一看[这里](http://stackoverflow.com/questions/5605125/why-is-iostreameof在进一步研究之前,请在内部环路条件下考虑错误)。 –
'!myFile.eof()'当你来到你的第二个循环时已经是真的。你至少要调用'myFile.clear()'和'myfile.seek(0)'来重新开始读取文件。 –
为什么你需要第二次?您可以在同一个循环中计算字母数量。 'while(myfile >> line){++ numberOfWords;字母+ = line.length(); }' – JustRufus