如果字符串的长度是在编译时确定的,我该如何正确初始化它?
#include <string>
int length = 3;
string word[length]; //invalid syntax, but doing `string word = " "` will work
word[0] = 'a';
word[1] = 'b';
word[2] = 'c';
…所以我可以做这样的事情?
示例:http: //ideone.com/FlniGm
我这样做的目的是因为我有一个循环将字符从另一个字符串的某些区域复制到一个新字符串中。
原文由 penu 发布,翻译遵循 CC BY-SA 4.0 许可协议
字符串是可变的,它的长度可以在运行时改变。但是如果你必须有一个指定的长度,你可以使用“填充构造函数”: http ://www.cplusplus.com/reference/string/string/string/
s6
现在等于 “xxxxxxxxxx” 。