Sign in to follow this  
Oni Sephiroth

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 this post


Link to post
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 this post


Link to post
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this