I want to do a program that checks the answer of a question. For example:
string ans1;
cout %26lt;%26lt; "How do you spell dog?\n";
getline(cin, ans1);
if(ans1==dog)
{
cout %26lt;%26lt; "correct\n";
}
when I do this program (with other required parts included)
I get errors saying that I need to identify dog, but if I do it skips over the if statement and ends the program
I have a simple C++ question about strings?
You have to understand the difference between a variable name and a string. In this case, you're asking for a comparison between the answer variable, ans1, and an undefined variable dog.
Now, if you had this statement:
if ( ans1 == "dog" )
you'd get further. Note the double quote marks around dog -- this isn't a variable, but what's called a literal constant.
This would work also if it was before your if statement:
string dog = "dog";
Hope that helps.
Reply:Hi. Hint. I think dog without any quotes (or other demarcation) is a variable, not a string. Not a C++ programmer.
Reply:You can start by asking the user for input. So create an input variable allowing the user to spell dog ( cin %26gt;%26gt; userinput1;) Then compare the results of the user answer to the results of ans1. If(ans1==userinput1)
// If the two answers match that you can use the cout %26lt;%26lt;"correct"\n;
Reply:if(ans1=="dog") or
char ans1[256];
cout %26lt;%26lt; "How do you spell dog?\n";
cin %26gt;%26gt; ans1 ;
if(!strcmp(ans1,"dog")
{
cout %26lt;%26lt; "correct\n";
}
Reply:you are comparing against 'dog' like it is a variable. You should use strcmp(ans1,dog) and check to make sure the value is 0. 0 means the strings are equal. strcmp stands for String Compare.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment