我现在遇到了一些问题,试图在设置c++字符串的一些值之后将char数组附加到c++字符串中,但我不明白为什么。我想知道你们中有没有人知道发生了什么。
下面是我试图运行的代码:
string test = "";
test.resize(1000);
char sample[10] = { "Hello!" };
test[0] = '1';
test[1] = '2';
test[2] = '3';
test[3] = '4';
test += sample;通过调试器运行它,似乎test只是"1234",而且从来没有添加过"Hello“。
提前感谢!
发布于 2016-02-27 23:13:20
它被添加了,但是在字符串中已经包含的1000个字符之后(其中4个是1234,996是'\0‘字符)。
resize函数确实为string对象分配了1000个字符,但也将长度设置为1000。这就是为什么有时候你想要做的是使用reserve
通常情况下,我会这样做:
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或者如果你想按自己的方式做:
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发布于 2016-02-27 23:21:04
我认为问题在于,当您执行test.resize(1000)时,它在字符串中添加了1000空字符('\0')。调试器可能将空字符视为字符串结束标记。因此,在这些空字符之后添加的任何文本都不会显示。
假设text等于这个('_' =空字符行标记结束):
test = "1234_______________Hello!";
^
Debugger thinks text ends herehttps://stackoverflow.com/questions/35676588
复制相似问题