我尝试了很多方法,但我仍然感到困惑。 我用char和string var替换“word”。 我把x中的单词放在另一个var中,但它失败了。 这段代码出了什么问题?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
char x[99];
fstream file;
file.open("data.txt",ios::in);
for (int i=1 ; !file.eof() ; i++) {
file.getline(x,99,' ');
if(x=="word")
cout << "found";}
file.close();
return 0;
}
答案 0 :(得分:0)
首先使用字符数组不是一个好主意,而是使用string.h并使用内置的OOP函数来处理文件中的文本。它会更容易
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
cout << "Write the path of the file\n" ;
string path ;
cin >> path ;
ifstream file(path.c_str()) ;
if(file.is_open()) //checking if files exists
{
cout << "Write the word you're searching for\n" ;
string word ;
cin >> word ;
int countwords = 0 ;
string candidate ;
while( file >> candidate ) // for each candidate word read from the file
{
if( word == candidate ) ++countwords ;
}
cout << "The word '" << word << "' has been found " << countwords << " times.\n" ;
return 0;
}
else
{
cout << "Error! File not found!\n" ;
return 1 ;
}
}