cout not printing full string?

Why does this code only return ss, as opposed to sss?

1
2
3
4
5
6
  int main () {
	string s="ss";
	s[2]='s';
	cout<<s;
}
try putting double quotes
Because s[2] isn't a part of the string, and you really shouldn't be doing this can lead to segmentation faults in larger programs.

You should be using the string concatenation operator or using a string function.

1
2
3
s+='s';
// or
s.append("s");
[2] is probably ok due to small string / other general luck that the class allocates a few bytes up front. So its probably not at risk of seg fault by happenstance. This does not make it a good idea to do this, as it WILL crash for some strings or some compilers.

why it does not work:
std::string outputs based off size, and size alone. cout on a string is effectively for(x = 0; x < size; x++) cout <<string[x] in terms of its behavior. You can see this by putting a zero in the middle of hello world. The output looks identical whether its a space or a null when printed, very unlike c-strings. And, you cannot manipulate size directly without mad hacks (and if you do THAT, you can still segfault if its not overallocated) -- resize does not work because it clears the new characters to zeros or a provided fill char. It would work if you could say size+= 1, but you can't. So even though your string's memory is "sss" it only has a size of 2 and you get 2 letters.

which is why the above answer is the right way to do it.

it would also work if you did resize first, and THEN set your specific letter to what you wanted. This is clunky and weird, and not 'normal' use of the class.

try this for fun and enlightenment
string s = "ss";
s.resize(3);
cout << s; //"ss";
cout << s; //now, what happened here? Do you understand?
s[2] = 's';
cout << endl;
cout << s; //and here. does it make sense?
and even if you see how this works, you still want
s+='s'; as the most common way to do this.
Last edited on
Registered users can post here. Sign in or register to post.