繁体   English   中英

打印所需的输出后,我的“c”代码打印出奇怪的东西

[英]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 循环之后。

还有两个潜在的问题:

  1. 你还没有做边界检查。 因此,如果您输入超过 1000 个字符,则arr可能会溢出。
  2. getchar()可以在输入失败时返回EOF ,您需要考虑到这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM