# Comparing strings... (C++)

## Recommended Posts

Having a little bit of a runtime issue...code first, explanation later. main.cpp
#include "command.h"

int main()
{
bool End = false;
char Input[16];
std::cout << "Harvest Engine SDK Build 1.0\n"
<< "For a list of commands type Comm.\n";

while (End == false)
{

std::cin >> Input;

if ( Input == "Comm")
{
std::cout <<"Command List:\n";
}
else if (Input == "Quit")
{
std::cout <<"Quiting...\n";
End = HVSTCOMM::Exit();
}
else
{
std::cout <<"Unkown command "<<Input<<"\n";
}

}

return 0;
}
Ok, so my issue is at runtime like I said above. If I type Comm in the console when prompted, it should be saying "Command List:". If I type Quit, the program should Exit. But, no matter what I type, it isn't recognizing them and it's going right to the else case (display "unkown command") So, what am I doing wrong here? Seems a little strange to me, unless I'm missing something..

##### Share on other sites
Comparing text that isn't stored in std::strings is more complicated than using ==. You are effectively comparing pointer values, and not the value in the string.

std::string is the best way, in general, of representing and storing text in C++. Unlike your char array, there is no arbitrary upper limit to the number of characters it can store (well, RAM is always a limiter [smile]).

Here is an example using std::string. It needs to be included in the <string> header (note: no file extension).
#include <string>#include "command.h"int main(){    bool End = false;    std::string Input;    std::cout << "Harvest Engine SDK Build 1.0\n"              << "For a list of commands type Comm.\n";    while (End == false)    {        std::cin >> Input;        if ( Input == "Comm")        {            std::cout <<"Command List:\n";        }        else if (Input == "Quit")        {            std::cout <<"Quiting...\n";            End = HVSTCOMM::Exit();        }        else        {            std::cout <<"Unkown command "<<Input<<"\n";        }    }}

To post source code in a pretty box, place [source][/source] tags around the code.

##### Share on other sites
That's odd, when I was using the string class earlier, I couldn't use cin >> with it...huh, well it's working this time around, so no complaints here. Thanks much.

##### Share on other sites
You don't really have a string in any case, you have a C character array. In C (which you're mixing-and-matching with C++ here), a character array isn't officially a string until you put on a null-terminator ('\0') on the end of it. Not only that, you're not comparing the contents of these arrays but the pointer values which is not what you're wanting to try and do.

Seriously, it's a pain in the arse as is 95% of C legacy stuff, rip-off's method is a much better solution. std::string was invented for a reason.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628390
• Total Posts
2982412

• 10
• 9
• 19
• 24
• 11