Fstream在文本文件中搜索单词

时间:2016-05-02 17:53:08

标签: c++

所以我必须让用户输入一个文本文件,我的程序应该搜索这个文本文件,一旦找到它,它就会在该文本文件中搜索一个单词,并计算一个单词的次数。数字出现在这个文件中。我在编写代码时遇到了问题,只是在文本文件中搜索单词。请帮忙。这就是我到目前为止所做的:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string dog;
    int word; 
    int TheFile; 



    cout << "enter the name of file and I'll search for it: " << endl;
    cin >> name;

    //opening the file
    TheFile.open(name, ios::out);

    if (file)
    {
        cout << "enter the word you want to search for: " << endl;
        cin >> word;
        getline(file, word);

//stuck here

        for (unsigned int Numline = 0; getline(TheFile, SearchWord);NumLine++)
            if (SearchWord.find)
    }
    else
    {
        cout << "the file " << NameofFile << " does not exist!" << endl;
        return 0;
    }
}

2 个答案:

答案 0 :(得分:0)

一旦你阅读了搜索词,你就想不管它。

之后,您希望将文件中的行读入其他(字符串)变量。然后,您要在该字符串中搜索搜索词(例如,使用input_line.find(search_word)

答案 1 :(得分:0)

这应该可以解决问题。使用while(getline(TheFile,Line))进行循环,然后使用string :: find在Line中搜索SearchWord。

#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
using namespace std;

int main()
{
    string name; 
    cout << "enter the name of file : " << endl;
    cin >> name;

    // opening the file
    fstream TheFile; 
    TheFile.open(name, ios::in);

    if (TheFile.is_open())
    {
        string word; // hold the word user inputs to be searched for
        cout << "enter the word: " << endl;

        string Line;
        unsigned int found = 0;
        while (getline(TheFile, Line)) {
            if (Line.find(word) != string::npos)
                ++found;
        }

        cout << "the word " << word << " was found " << found << " times" << endl;
    }
    else
    {
        cout << "the file " << name << " does not exist!" << endl;
    }

    cout << "press enter to exit " << endl;
    int c = getch();
    return 0;
}
相关问题