C and C++ do not really provide the feasible option of comparing two C-style strings by just using the '==' operator. I'm sure a book or one of the fine persons on this site can give a much better explanation of exactly why that is, but here are a couple of things you can do in the meantime to make your code work.
I do not know how much you have fiddled with the C++ string class, but it offers some good string comparison and manipulation functions that can be incredibly useful. One such function:
- Code: Select all
strcmp( const char *_str1, const char *_str2 )
Takes two null-terminated strings and compares them. It returns 0 if they are identical, < 0 if string1 is less than string2, and > 0 if string1 is greater than string2. You could use that in this fashion:
- Code: Select all
#include <iostream>
#include <string> // You must include the string header to use strcmp()
int main()
{
char password[50] = "lolcat"; // The word is stored in the variable this time
char guess[10]; // The user's guess is stored here for comparison
while( 1 ) // The way I use while loops, but it does not matter so much here
{
std::cout << "enter password ";
std::cin >> guess;
// If the function returns 0, they are identical
if( strcmp( password, guess ) == 0 )
{
std::cout << "yay you got the password!!!!!" << std::endl;
break; // Break out of the while loop
}
// Else if the function does not return 0, they are not identical
else if ( strcmp( password, guess ) != 0 )
{
std::cout << "thats not the correct password, you suck!!" << std::endl;
}
}
system("PAUSE");
return 0;
return EXIT_SUCCESS;
}
An alternate way that you could utilize the string header would be to use the C++ string class, since it actually does offer direct comparison with the '==' operator. A nice quality of the string variable is also that you do not need to state how long the array is expected to be. That means that theoretically you could store any length character array in the string you need; essentially, you tell it first what you want it to be, and then it determines all on its own how long it needs to be to do what you want.
- Code: Select all
#include <iostream>
#include <string> // You must include the string header to use the string object
int main()
{
// Here are our new string variables; notice there is no pre-determined length
std::string password = "lolcat";
std::string guess;
while( 1 )
{
std::cout << "enter password ";
std::cin >> guess;
if( guess == password )
{
std::cout << "yay you got the password!!!!!" << std::endl;
break;
}
else if ( guess != password )
{
std::cout << "thats not the correct password, you suck!!" << std::endl;
}
}
system("PAUSE");
return 0;
return EXIT_SUCCESS;
}
I hope that helps. If you have any other questions, feel free to ask.