#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream inputFile; // input file
inputFile.open ("/tmp/word");
char randomword[21], userword;
inputFile.getline (randomword, 20);
cout << "Enter your word: ";
cin >> userword;
if (randomword == "userword"){
cout << "The word you entered matches the random word."<< endl;
}
elseif (randomword != "userword"){
cout << "The word you entered does not match the random word." << endl;
}
return 0;
}
Ok there's my code. The program is basically supposed to have the user select a word then match it with the word in the "word" file. When I run my program it only displays only "The word you entered does not match the random word" even if the word matches. Any suggestions?
When I run my program numerous times. It will always display the same random word until I log out of the server and log back in. That's why I can anticipate what the word is going to be.
#include <string> // <- include string
int main()
{
ifstream inputFile; // input file
inputFile.open ("/tmp/word");
/* get rid of this
char randomword[21], userword;
inputFile.getline (randomword, 20);
*/
// use this:
string randomword, userword;
getline( inputFile, userword );
cout << "Enter your word: ";
cin >> userword;
if (randomword == userword){ // < -get rid of the quotes here
cout << "The word you entered matches the random word."<< endl;
}
else /*if (randomword != "userword"){*/ // <- get rid of the entire condition here (it's redundant)
cout << "The word you entered does not match the random word." << endl;
}
return 0;
}
Also please note that the usual C function for comparing strings is strcmp(), you can't compare character arrays using "==" (you can do that for c++ strings as std::string class have overloaded == operator).