2013-06-05 127 views
1

我面临这个位置,我需要创建一个用户输入大小的动态字符串(所以我尝试使用动态cstring)。创建一个动态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空间和一些随机字符我该如何解决这个问题?

+5

尝试在字符串的末尾添加“\ 0”。 – austin

+1

为什么不使用std :: string? CString也是由微软制作的一个类,char *就是你在那里的东西。 – olevegard

+1

@olevegard我认为他的意思是说'C字符串'。 – SevenBits

回答

1

扩展我以前的评论。我认为您需要在最后添加一个空字符,以便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'; 
+0

谢谢@austin:D我忘了null – Ezz