【发布时间】:2018-12-04 07:57:17
【问题描述】:
在下面的程序中,当我向字符串添加一个字符时,它的大小仍然保持不变(从 str1.size() 函数可以看出)。这是为什么呢?
#include <iostream>
#include <cstring>
using std::cout;
using std::endl;
int main() {
std::string str1 = "hello";
cout << "std::string str1 = \"hello\""<< endl;
cout << "string is " << str1 << " with length " << str1.size() << endl;
str1[5] = 'a';
cout << "string is " << str1 << " with length " << str1.size() << endl;
for (int i = 0 ; i < 7; i++) {
cout << "str["<<i<<"] = " << str1[i] << " (int)(str[i])" << (int)str1[i] << endl;
}
}
输出
std::string str1 = "hello"
string is hello with length 5
string is hello with length 5 //expected 6
str[0] = h (int)(str[i])104
str[1] = e (int)(str[i])101
str[2] = l (int)(str[i])108
str[3] = l (int)(str[i])108
str[4] = o (int)(str[i])111
str[5] = a (int)(str[i])97
str[6] = (int)(str[i])0
【问题讨论】:
-
当我在字符串中再添加一个字符时 -- 你在哪里做呢?您的程序中没有“添加字符”。
-
这种误解正是为什么教 C++ 的人不应该从 C 开始的原因。从
int、std::string和std::vector开始教 C++ 并完成任务。向量或字符串的实际外观以及如何在 C++ 中使用 C 的东西很有趣,但更高级。std::vector<std::string> args(argv + 1, argv + argc);应该是最早教授的语句之一,因此练习可以包括基本的参数处理。