检查文本文件c ++中是否存在单词

Gle*_*654 6 c++ text file

我需要检查字典文本文件中是否存在一个单词,我想我可以使用 strcmp,但我实际上不知道如何从文档中获取一行文本。这是我目前坚持使用的代码。

#include "includes.h"
#include <string>
#include <fstream>

using namespace std;
bool CheckWord(char* str)
{
    ifstream file("dictionary.txt");

    while (getline(file,s)) {
        if (false /* missing code */) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

Sof*_*ner 5

std::string::find做这个工作。

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

using namespace std;

bool CheckWord(char* filename, char* search)
{
    int offset; 
    string line;
    ifstream Myfile;
    Myfile.open (filename);

    if (Myfile.is_open())
    {
        while (!Myfile.eof())
        {
            getline(Myfile,line);
            if ((offset = line.find(search, 0)) != string::npos) 
            {
                cout << "found '" << search << "' in '" << line << "'" << endl;
                Myfile.close();
                return true;
            }
            else
            {
                cout << "Not found" << endl;
            }
        }
        Myfile.close();
    }
    else
        cout << "Unable to open this file." << endl;

    return false;
}


int main () 
{    
    CheckWord("dictionary.txt", "need");    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Sid*_*gal 2

char aWord[50];
while (file.good()) {
    file>>aWord;
    if (file.good() && strcmp(aWord, wordToFind) == 0) {
        //found word
    }
}
Run Code Online (Sandbox Code Playgroud)

您需要使用输入运算符来读取单词。