简体   繁体   English

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

[英]My 'c' code prints weird stuff after printing the required output

My code is about saying one sentence about Berlin .. Part of this sentence starts with "Berlin " and the other part is from standard input from the user .. after printing the output .. I get weird random things like "w$我的代码是关于说一个关于柏林的句子..这句话的一部分以“柏林”开头,另一部分来自用户的标准输入..打印输出后..我得到奇怪的随机东西,比如“w$

Here is my code :这是我的代码:

#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;
}

You haven't included the null terminator for arr (since you are printing it as a C-string using %s ).您尚未为arr包含空终止符(因为您使用%s将其打印为 C 字符串)。

Add添加

arr[i] = 0;

after the while loop.在 while 循环之后。

There are two other potential problems:还有两个潜在的问题:

  1. You haven't done bounds check.你还没有做边界检查。 So arr could overflow if you enter more than 1000 chars.因此,如果您输入超过 1000 个字符,则arr可能会溢出。
  2. getchar() can return EOF on input failure which you need to take into account. getchar()可以在输入失败时返回EOF ,您需要考虑到这一点。

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

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