Suzan Aydın
Suzan Aydın

Reputation: 363

String to Char Array not working

I noticed that if my string is empty, the char array does not become empty either. See the below code:

std::copy(strUsername.begin(), strUsername.end(), sRecord.m_strUsername);

sRecord.m_strUsername is a char[1064], but if it is already populated and i try doing a copy (or strcpy) with strUsername as empty, nothing happens, even though I want sRecord.m_strUsername to become empty or just become whatever strUsername is.

Upvotes: 0

Views: 254

Answers (2)

Baum mit Augen
Baum mit Augen

Reputation: 50111

You forgot the zero terminator:

std::copy(strUsername.begin(), strUsername.end(), sRecord.m_strUsername);
sRecord.m_strUsername[strUsername.size()] = '\0';

or alternatively

std::strcpy(sRecord.m_strUsername, strUsername.c_str() );

or if you want all "unused" characters of your array to be \0:

std::copy(strUsername.begin(), strUsername.end(), sRecord.m_strUsername);
std::fill(sRecord.m_strUsername + strUsername.size(), 
          sRecord.m_strUsername + 1064, '\0');

The latter is usually not necessary since C-style strings are commonly defined as a range like [sRecord.m_strUsername[0], first '\0' in the array). What comes after the first \0 usually does not matter unless you want to access that for whatever reason.

The range [str.begin(), str.end()) only contains all the characters of the string. A C-style string (aka array of char) requires an additional '\0'-termination character.

With my first and second proposed fix, the range [sRecord.m_strUsername[0], first '\0' in the array) will be equal to the characters in strUsername as long as the latter does not contain any additional '\0's (something you just cannot easily deal with with C-style strings).

With my third proposed fixed, every character in the array after all the characters from your string will be \0.

Important note: Before doing any of the above, you need to assert that your string contains at most 1063 characters! If this is not certain, raise some kind of error if the assumption does not hold or use std::strncopy instead. strncopy will basically behave like my third snippet, but you have to zero the last element of your array yourself.

Upvotes: 4

flogram_dev
flogram_dev

Reputation: 42888

You can use strcpy which automatically copies the terminating null character as well, and std::string::c_str:

std::strcpy(sRecord.m_strUsername, strUsername.c_str());

So if strUsername is empty (""), m_strUsername will also be equal to "" after that call.

Upvotes: 1

Related Questions