[英]My 'c' code prints weird stuff after printing the required output
我的代码是关于说一个关于柏林的句子..这句话的一部分以“柏林”开头,另一部分来自用户的标准输入..打印输出后..我得到奇怪的随机东西,比如“w$
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (){
#define MAX 1000
char arr [MAX] ;
char star [] = "Berlin ";
int i = 0;
while ((arr[i] = getchar()) != '\n') {
i++;
}
printf("%s%s", star,arr);
return 0;
}
您尚未为arr
包含空终止符(因为您使用%s
将其打印为 C 字符串)。
添加
arr[i] = 0;
在 while 循环之后。
还有两个潜在的问题:
arr
可能会溢出。getchar()
可以在输入失败时返回EOF
,您需要考虑到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.