Skip to main content
gamedev.net
🔒 Locked

std::string

Started by mago 5 replies 600+ views
Original Post
mago
mago
I have an object stored in a file. This object has a member std::string variable strName. In the constructor of this object, I obtain a char *Str which contains a string that I want to store in strName. But when I write strName = Str, the program crashes . Why? I think it''s probably because first I have to allocate some space for the strName. But if yes, how? thanx
thanx for sharing
invective
invective
If you are talking about something like this:

  
void main (void)
{

char *characterArray = "This is a place holder\n";
std::string myString = characterArray;
std::cout << myString;
}


Then it definately should work, because operator = is overloaded to make the proper conversion to std::string from char * and the string class is smart enough to allocate memory for itself (you could try reserve() still if you want). Maybe something else is wrong with your code? You have a pointer to std::string instead or std::string or you left out the ''\0'' in the char* ? try posting the relavant portion of your code.
Bunnz
Bunnz
Get sure that Str is filled with a valid string!!!

char *Str = "Test";
string strName;
strName = Str;
is correct

Have fun
Bunnz

Visit: www.bunnz.com
Have fun BunnzPunch'n'Crunch
mago
mago
Ok the whole thing looks like this:



CObject::CObject(HANDLE hFile)

:m_strName("");

{

char name[100];

unsigned long size;



// read size of the following string

ReadFromFile(hFile, &size, sizeof(unsigned long));



// read the string itself

ReadFromFile(hFile, name, size);

name[size] = 0; // terminating the string



m_strName = name; // crashes here

};

ReadFromFile is my own function and works perfectly, I''m also sure that the name[] gets filled properly.... Now why does it crash....
thanx for sharing
Silvanis
Silvanis
name[size] = 0; // terminating the string

try name[size] = /0;

0 is just a char, /0 is the null character for a sting.
VolkerG
VolkerG
0 or ''\0'' shouldn''t make any difference. But have you checked if name contains the correct string (by using a debugger)?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.