string and answers...

Jul 29, 2009 at 1:48pm
hey guys ive been reading the pdf tutorial and i checked the "if and else" and i wanted to know if i can do this:
1
2
3
4
5
6
7
8
string mystring = "are you okay";
cout << mystring << " ";
if ("yes")
   then
     cout << "ohh then lets keep talking";
else
  then
   cout << "Whatever";

All i want to know if the person says "yes" can i answer something and if it says something else i can say something different than the first answer of yes AND terminate the program
Last edited on Jul 29, 2009 at 5:31pm
Jul 29, 2009 at 2:06pm
You need to get input and to check a proper condition:
1
2
3
4
5
6
7
string mystring;
cout << "are you okay? ";
cin >> mystring; // get input ( http://www.cplusplus.com/forum/articles/6046/ )
if ( mystring == "yes" )
     cout << "ohh then lets keep talking";
else
   cout << "Whatever";
Jul 29, 2009 at 2:16pm
On line 3 you are evaluating the truth value of the C-style string "yes", { 'y', 'e', 's', '\0' }, it's basically a pointer to the first character, and indeed a pointer pointing to an allocated memory (so not a NULL pointer).

Because it's not NULL, if ("yes") always evulates true.

You actually mean something like this:
1
2
3
4
string response;
cin >> response;
if (response == "yes")
   // do something... 


You don't need the word then in C++.
Jul 29, 2009 at 2:38pm
ohh okay i wanted to know only thx for the answer... the thenwas for a explanatory subject:)
Topic archived. No new replies allowed.