我所面临的位置是,我需要创建一个用户输入大小的动态字符串(所以我尝试使用动态cstring)。
char * S;
int x;
cin >> x;
S = new char[x];
for (int i = 0; i < x; i++) {
S[i]=' '; //trying to make it a string of spaces so I can fill it in later
}在这样做并输出字符串(cout << S;)时,我得到了x个空格和一些随机字符,我该如何解决这个问题呢?
发布于 2013-06-06 03:29:39
延伸我之前的评论。我认为您需要在末尾添加一个空字符,以便std::cout知道何时停止,否则它将继续尝试打印S所指向的内存内容。
char * S;
int x;
cin >> x;
S = new char [x + 1]; // +1 for the null character
int i;
for (i=0; i<(x); i++)
S[i] = ' ';
S[i] = '\0';https://stackoverflow.com/questions/16948028
复制相似问题