如何在c ++中搜索文档中的字符串?

Sou*_*lly 3 c++ fstream ifstream ofstream

到目前为止,这是我的代码:

#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main()
{
    int count = 0;
    string fileName;
    string keyWord;
    string word;


    cout << "Please make sure the document is in the same file as the program, thank you!" 
         << endl << "Please input document name: " ;
    getline(cin, fileName);
    cout << endl;

    cout << "Please input the word you'd like to search for: " << endl;
    cin >> keyWord;
    cout << endl;
    ifstream infile(fileName.c_str());
    while(infile.is_open())
    {
        getline(cin,word);
        if(word == keyWord)
        {
            cout << word << endl;
            count++;
        }
        if(infile.eof())
        {
            infile.close();
        }

    }
    cout << count;

}
Run Code Online (Sandbox Code Playgroud)

我不知道如何进入下一个词,目前这个无限循环...任何建议?

另外......如何告诉它打印出该单词所在的行?

提前致谢!

Ara*_*raK 7

while(infile >> word)
{
    if(word == keyWord)
    {
        cout << word << endl;
        count++;
    }
}
Run Code Online (Sandbox Code Playgroud)

这样就可以了.请阅读更多关于流的信息.