【问题标题】:Checking if word exists in a text file c++检查文本文件中是否存在单词c ++
【发布时间】:2012-11-09 01:36:14
【问题描述】:

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

【问题讨论】:

    标签: c++ file text


    【解决方案1】:

    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;
    }
    

    【讨论】:

    • 这仅检查是否在第一行找到,如果在文件末尾找到您搜索的单词怎么办?您将如何修复上述代码?
    • @unixcreeper 正如我所见,它检查所有行,如果它在一行中找到它,如果没有“未找到”,它会说基金并再次运行搜索,直到 EOF(文件结尾)。
    【解决方案2】:
    char aWord[50];
    while (file.good()) {
        file>>aWord;
        if (file.good() && strcmp(aWord, wordToFind) == 0) {
            //found word
        }
    }
    

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

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    相关资源
    最近更新 更多