English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I want to do a program that checks the answer of a question. For example:

string ans1;

cout << "How do you spell dog?\n";
getline(cin, ans1);

if(ans1==dog)
{
cout << "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

2007-10-15 11:12:52 · 5 answers · asked by j_ririe20 1 in Computers & Internet Programming & Design

5 answers

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.

2007-10-15 11:22:20 · answer #1 · answered by The Phlebob 7 · 0 0

You can start by asking the user for input. So create an input variable allowing the user to spell dog ( cin >> 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 <<"correct"\n;

2007-10-15 21:19:39 · answer #2 · answered by ShyShy 2 · 0 0

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.

2007-10-15 18:17:13 · answer #3 · answered by Haley 5 · 0 0

if(ans1=="dog") or

char ans1[256];

cout << "How do you spell dog?\n";
cin >> ans1 ;

if(!strcmp(ans1,"dog")
{
cout << "correct\n";
}

2007-10-15 18:18:02 · answer #4 · answered by Django L 2 · 1 0

Hi. Hint. I think dog without any quotes (or other demarcation) is a variable, not a string. Not a C++ programmer.

2007-10-15 18:16:54 · answer #5 · answered by Cirric 7 · 1 0

fedest.com, questions and answers