索引到字符串时输出不正确

Incorrect output when indexing into a string

我有一些这样的代码:

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

它给了我想要的,也就是12.1.2.

但是下面的代码:

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

它没有给我想要的东西。它的输出是.1.2.

这是为什么?我以为应该是12.1.2.

顺便说一句,我正在用 QTcreator 5.4 来做这件事。这重要吗?

提前致谢!

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

这看起来像是未定义的行为。也许你应该使用 at to trigger the out_of_range 例外 :)

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

它会在 OS X 上产生以下结果(因为我 没有 捕获异常):

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

你可以用类似的东西修复它:

string ss = "  ";    // two blanks spaces

或者:

string ss;
ss.resize(2);