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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13482464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:22:29  来源:igfitidea点击:

Checking if word exists in a text file c++

c++filetext

提问by Glen654

I need to check if a word exists in a dictionary text file, I think I could use strcmp, but I don't actually know how to get a line of text from the document. Here's my current code I'm stuck on.

我需要检查字典文本文件中是否存在一个单词,我想我可以使用 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;
}

采纳答案by Sidharth Mudgal

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

You need to read words with the input operator.

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

回答by Software_Designer

std::string::finddoes the job.

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 << " \n\n"<< line  <<endl;
             return true;
            }
            else
            {

                cout << "Not found \n\n";

            }
        }
        Myfile.close();
    }
    else
    cout<<"Unable to open this file."<<endl;

    return false;
}


int main () 
{

    CheckWord("dictionary.txt", "need");

    return 0;
}