user3713215
user3713215

Reputation: 41

std::string assignment through index doesn't seem to work

in c++

when I declare

string string1;

then I'm not able to assign by index as in

string1[0] = 'x';

however if I first put string1 = "somestring"; then I am able to use the assignment through index.

string = ""; 

doesnt work

so I'm wondering why is this. I thought std::string was supposed to have index functionality.

Upvotes: 1

Views: 681

Answers (2)

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6039

When you have string string1; you are declaring an empty string. You have to assign a value to it before you can access a character of the string through an index.

It won't create index 0 of an empty string for you just by string1[0] = 'x'; It will, however allow you to change the value at index 0 if there are characters already there in the string.

You can create a 'preallocated' string of sorts through the constructor: string (size_t n, char c); where n is the number of characters to copy and c is the character to fill the string with. So, for example, you could have std::string string1(5, ' '); which would create a string filled with 5 spaces. You could then use any index from 0-4 in order to put other values in the string (as in your original question - string1[0] = 'x';). http://www.cplusplus.com/reference/string/string/string/

Upvotes: 2

David
David

Reputation: 28188

When you default construct a string, it's empty. There are no elements its char array, so [0] doesn't exist. If you construct it by giving it a string, like "somestring", it contains that string and the zeroth index is s.

Upvotes: 2

Related Questions