7

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;
}
Glen654
  • 1,102
  • 3
  • 14
  • 18

2 Answers2

5

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;
}
Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
Software_Designer
  • 8,490
  • 3
  • 24
  • 28
  • This only checks if its found on the first line, what if the word your searching for is found at the end of the file? How would you fix the above code? – unixcreeper Jan 26 '17 at 16:00
  • @unixcreeper As I can see it checks all lines, if it finds in a line it says fund if not "not found" and runs search again until EOF (end of the file). – Giorgi Gvimradze May 18 '17 at 22:43
2
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.

Sidharth Mudgal
  • 4,234
  • 19
  • 25
  • 1
    Test w/ [Lopado­temacho­selacho­galeo­kranioleipsano­drim­hypo­trimmato­silphio­parao­melito­katakechy­meno­kichl­epikossypho­phatto­peristeralektryon­opte­kephallio­kigklo­peleio­lagoio­siraio­baphe­traganopterygon](http://en.wikipedia.org/wiki/Lopado%C2%ADtemacho%C2%ADselacho%C2%ADgaleo%C2%ADkranio%C2%ADleipsano%C2%ADdrim%C2%ADhypo%C2%ADtrimmato%C2%ADsilphio%C2%ADparao%C2%ADmelito%C2%ADkatakechy%C2%ADmeno%C2%ADkichl%C2%ADepi%C2%ADkossypho%C2%ADphatto%C2%ADperister%C2%ADalektryon%C2%ADopte%C2%ADkephallio%C2%ADkigklo%C2%ADpeleio%C2%ADlagoio%C2%ADsiraio%C2%ADbaphe%C2%ADtragano%C2%ADpterygon)! – HostileFork says dont trust SE Nov 20 '12 at 22:02