Hayden Taylor
Hayden Taylor

Reputation: 65

C++ string appending problems

I'm having some issues right now, attempting to append a char array onto a c++ string after setting some of the values of the c++ string, and I don't see why. I was wondering if any of you know what's going.

Here's the code I'm trying to run:

string test = "";
test.resize(1000);
char sample[10] = { "Hello!" };
test[0] = '1';
test[1] = '2';
test[2] = '3';
test[3] = '4';
test += sample;

Running it through a debugger, it seems that test is just "1234", and the "Hello" is never added.

Thanks in advance!

Upvotes: 0

Views: 373

Answers (2)

Galik
Galik

Reputation: 48615

I think the problem is when you did test.resize(1000) it added 1000 null characters ('\0') to the string. The debugger probably sees null characters as end-of-string markers. So any text added after those null characters won't get displayed.

Say text equals this ('_' = null character end of line marker):

test = "1234_______________Hello!"; 
            ^
            Debugger thinks text ends here

Upvotes: 0

Jts
Jts

Reputation: 3527

It is added, but after the 1000 characters you already have in the string (4 of them are the 1234, and 996 are '\0' characters)`.

The resize function does allocate 1000 characters for the string object, but also sets the length to 1000. That's why sometimes what you want to do instead is use reserve

This is normally what I would do:

string test = "";
test.reserve(1000); // length still 0, capacity: 1000
char sample[10] = { "Hello!" };
test.push_back('1'); // length is 1
test.push_back('2'); // length is 2
test.push_back('3'); // length is 3
test.push_back('4'); // length is 4
test += sample; // length is now 10

Or if you want to do it your way:

string test = "";
test.resize(1000); // length is 1000
char sample[10] = { "Hello!" };
test[0] = '1'; // length is 1000
test[1] = '2'; // length is 1000
test[2] = '3'; // length is 1000
test[3] = '4'; // length is 1000
test.resize(4); // length is now 4, but the internal buffer still has a capacity of 1000 characters
test += sample; // length is now 10

Upvotes: 3

Related Questions