Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if word exists in a text file c++

Tags:

c++

file

text

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.

#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;
}
like image 511
Glen654 Avatar asked Nov 20 '12 21:11

Glen654


2 Answers

std::string::find does the job.

#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;
}
like image 87
Software_Designer Avatar answered Nov 14 '22 01:11

Software_Designer


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.

like image 23
Sidharth Mudgal Avatar answered Nov 13 '22 23:11

Sidharth Mudgal