我对算法的时间复杂性不熟悉。 这是用于计算文本文件中的单词数的代码。 我的问题是,每次我的程序打印的文件超过文件中实际的单词数量时,就像我的文件中有11个单词一样,它打印12个。
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
/* main function */
void main()
{
ifstream inFile; //file file name
string fileName;
string word;
int count = 0;
inFile.open("example.txt");
while(!inFile.eof())
{
inFile >> word;
++count;
}
cout << "Number of words in file is " << count<<endl;
inFile.close();
}
//this file is for counting the number of words in a text file**
答案 0 :(得分:1)
第一件事:Why is iostream::eof inside a loop condition considered wrong? 这将回答你的额外计数问题。 子>
然后,复杂化,因为它将遍历每N个字直到它到达文件末尾,它将在 O(N)时间内完成
此外,void main()
不是 legal c ++,main应返回int