因此,我被要求这样做,我这样做是这样的:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int N,i;
printf("Give the number of char's you want to input.\n");
scanf("%d",&N);
char *str = (char*) malloc(N);
//this segment inputs the char's to the string.
printf("Input the char's.\n");
for (i=0;i<N;i++)
{
str[i] = getchar();
}
str[N] = '\0';
}
由于我很喜欢c,所以我想知道是否还有其他/更好的方法可以做到这一点。提前致谢。
使用可变长度数组(在C99和更高版本中允许)或使用动态内存分配。您的方法是使用VLA。您还可以动态地执行以下操作:
int N;
printf("Give the number of char's you want to input.\n");
scanf("%d",&N);
char *str = malloc(N+1);
旁注:
main
为其正确的签名int main(void)
。0
C开始。初始化i
为,0
而不是,1
将上限设置为i < N
。将for
循环更改为for (int i = 0; i < N; i++) { str[i] = scanf(" %c"); } str[N] = '\0';
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句