RunUO Community

This is a sample guest message. Register a free account today to become a member! Once signed in, you'll be able to participate on this site by adding your own topics and posts, as well as connect with other members through your own private inbox!

C++ Problem

C++ Problem

Code:
#include <iostream>

using namespace std;
int main()
{
	char string[6];
	cout << "enter string: ";
	gets(string);
	if(string == "string")
		cout << "true";
	else
		cout << "false";
	return 0;
}
I enter string and it returns false and crashes...any ideas? I believe that I'm using an incorrect method to compare a literal(?) string to a collection of characters. But I'm unsure of any other way to do this. Help appreciated.
 

Jeff

Lord
Storm33229;780388 said:
Code:
#include <iostream>

using namespace std;
int main()
{
	char string[6];
	cout << "enter string: ";
	gets(string);
	if(string == "string")
		cout << "true";
	else
		cout << "false";
	return 0;
}
I enter string and it returns false and crashes...any ideas? I believe that I'm using an incorrect method to compare a literal(?) string to a collection of characters. But I'm unsure of any other way to do this. Help appreciated.
C++ Strings [C++ Reference]
 

Spidey

Wanderer
Just change char string[6]; to char string[7];

"string" actually is {'s', 't', 'r', 'i', 'n', 'g', '\0'}
 

gilgamash

Knight
But it will crash again if you enter a longer string. Problem is the allocation of memory in this case. I recommend using the string class (header <cstring> for Linux, OSX, Win, QNX, ...) to avoid such problems or just allocate enough memory for whatever input might be entered.
 
Top