使用 scanf 存储字符串时出现问题

Problems storing strings with scanf

我在 C 语言中使用 scanf 时遇到问题。在阅读了有关如何解决 scanf 问题的其他 Whosebug 帖子后,我现在知道不建议使用 scanf,但是我必须将它用于家庭作业。我正在尝试根据缓冲区大小存储 3 个具有最大大小的字符串值。当我编译并 运行 这个程序时,我输入值 255 255 255,这就是打印的内容。

1:
2:
3: 255

这里是程序源:

#include <stdio.h>
int main(){
     char first[8] = "", second[3] = "", third[3] = "";
     scanf("%8s %3s %3s", first, second, third);
     printf("1: %s\n2: %s\n3: %s", first, second, third);
}

按照目前的定义,数组只能存储非常短的字符串:

  • char first[8]只能存储7个字节和一个空终止符,
  • char second[3]只能存储2个字节和一个空终止符,
  • char third[3] 只能存储 2 个字节和一个空终止符。

scanf 格式字符串应为:

scanf("%7s %2s %2s", first, second, third);

当前代码调用未定义的行为,因为您存储的字符串长度超过 secondthird 的数组大小。

要解析更长的字符串,您应该将数组定义为

char first[9] = "", second[4] = "", third[4] = "";

并且您应该检查 scanf() 的 return 值。