Hi all.
I'm trying to write a "simple" program for a word game (something somewhat similar to Scrabble) and I got stopped by the task I tought to be easy enough to start with.
I have a text file (Italiano.list) wich is a collection of italian words listed alphabetically as below:
a
ab
abaca
abache
abachi
abacista
abaciste
abacisti
abaco
...
What I would like it to do is to let the user input a string (word) and then search for that word in the "dictionary". Obviously it should also tell if the word is present or not.
Here's what I wrote so far: it seems to me to be logical and quite simple but evidently there's something I am missing... I think it opens correctly the file and it stores as expected each line in the string current_word (substituting the 2nd if with a simple "cout << current_word << endl;" makes it print the whole dictionary on screen) but then it fails in comparison because it always state that the word is not present... even if that particular word actually IS present! Also at line 21 there is another curious error... comment should explain it.
Btw, thanks in advance for every hint or try you'll eventually give to me and sorry as always for my english.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(void) {
string key;
string current_word;
ifstream dictionary("Italiano.list");
cout << "Quale parola si vuole cercare?" << endl; // asks for a key
cin >> key;
cout << "La parola che si sta cercando e' la seguente: " << key << endl; // prints the key to checkif it's typed correctly
if(!dictionary.is_open()) {
cout << "Errore. Impossibile accedere al dizionario." << endl; // exits with error for not being able to open the dictionary
return 1;
}
while(!dictionary.eof()) {
getline(dictionary, current_word); // stores the current line of the dic in the current_word string...
if(current_word==key) { // ... and then compares it with the user input
cout << current_word << endl;
cout << "La parola " << current_word << " e' uguale alla parola cercata." << endl; /* line 21: I wanted it to print the string stored in current_word in the case of matching with the user input for another check but it prints actually only " " e' uguale alla parola cercata." << endl; " ! Don't know why, because in the previous line it prints correctly the string current_word... */
cout << "La parola cercata e' presente nel dizionario." << endl; // tells that the word searched for has been found in the dictionary
dictionary.close();
return 0;
}
}
dictionary.close();
cout << "La parola cercata non e' presente nel dizionario." << endl; // tells that the word searched for has not been found in the dictionary.
return 0;
}
Edit: here's the link to where I learned that tiny little bit of handling files I've tried to use in this program: http://www.cplusplus.com/doc/tutorial/files.html