Home  >  Q&A  >  body text

c++ - C 语言 gets() 和 printf() 的问题

当我输入一串字符

    char str[10];
    printf("Input a string.\n");
    gets(str);
    printf("The string you input is: %s",str);

当我输入的字符串长度大于0 的时候,输出结果是这样的

1ang:lab lang$ ./exercise 
Input a string.
warning: this program uses gets(), which is unsafe.
0123456789
Abort trap: 6

但是我加了 \n, printf("The string you input is: %s\n",str); 输出的结果就不一样了

1ang:lab lang$ ./exercise 
Input a string.
warning: this program uses gets(), which is unsafe.
0123456789
The string you input is: 0123456789
Abort trap: 6

它会先printf然后再报错, 这是为什么?(编译器是GCC)

大家讲道理大家讲道理2713 days ago524

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:27:28

    Strings in C use the null character as the end, so you need to allocate one more character of space when allocating the array. The error is reported because your input 0123456789 has a total of 10 characters, plus the automatically added null character at the end, a total of 11 characters, and your array size is only 10, so it is out of bounds.

    In addition, the gets function has been abolished since the 11-year standard. Please use other functions, such as scanf, std::getline, std::cin, etc. to read strings.

    reply
    0
  • Cancelreply