TMIbuddy
TMIbuddy

Reputation: 13

Incorrect output when indexing into a string

I have some code like this:

string s = "ab";
s[0] = '1';
s[1] = '2';
cout << s << "." << s[0] << "." << s[1] << "." << endl;

It gives me what I want, which is 12.1.2.

But the following code:

string ss = "";
ss[0] = '1';
ss[1] = '2';
cout << ss << "." << ss[0] << "." << ss[1] << "." << endl;

It doesn't give me what I want. Its output is .1.2.

Why is that? I thought it should be 12.1.2.

BTW, I'm doing that with QTcreator 5.4. Does that matter?

Thanks in advance!

Upvotes: 1

Views: 69

Answers (1)

jww
jww

Reputation: 102346

string ss = "";
ss[0] = '1';
ss[1] = '2';
cout << ss << "." << ss[0] << "." << ss[1] << "." << endl;

This looks like undefined behavior. Perhaps you should use at to trigger the out_of_range exception :)

string ss = "";
ss.at(0) = '1';
ss.at(1) = '2';
cout << ss << "." << ss[0] << "." << ss[1] << "." << endl;

It results in the following on OS X (because I am not catching the exception):

$ ./cxx-test.exe
libc++abi.dylib: terminate called throwing an exception
Abort trap: 6

You can fix it with something like:

string ss = "  ";    // two blanks spaces

Or:

string ss;
ss.resize(2);

Upvotes: 2

Related Questions