Computing.Net > Forums > Programming > Simple C++

Simple C++

Reply to Message Icon

Original Message
Name: ipartyin247
Date: March 9, 2007 at 08:59:36 Pacific
Subject: Simple C++
OS: Vista
CPU/Ram: Athlon 64 3800+/ 1 GB DDR
Model/Manufacturer: HP Pavillion a1709n
Comment:

I am new to c++ so bear with me, how do I do an if else statement with a string?

such as

if string == "This is what you type"
cout << "yes";
else
cout << "no";

i tried it and it always just displays my if statement i believe. im not home to look at it at the moment. thanks.

-CG


Report Offensive Message For Removal

Response Number 1
Name: cup
Date: March 9, 2007 at 13:07:53 Pacific
Subject: Simple C++
Reply: (edit)

What type of strings are you using? There are two types: a character string and an STL string. First, the character string. If you have

const char* string = "Not quite";
if (string == "Not quite")
cout << "yes" << endl;
else
cout << "no" << endl;

will always print no since you are just comparing addresses. To compare character strings use the C function strcmp

if (strcmp(string, "Not quite") == 0)
...

If you are using STL strings, you shouldn't name your variable string. Let us call it cs.

std::string cs = "Not quite";
if (cs == "Not quite") ...

In this case it will print yes.


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Simple C++ 

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software