请提供一个能使两个C程序产生不同输出的测试用例
差异测试用例及分析
现有两个C程序,二者的scanf输入处理逻辑存在差异,以下是能让它们输出不一致的测试用例及具体分析。
程序1代码
#include <stdio.h> #define MAXSTR 100 int main() { char ch; char str[MAXSTR]; char line[MAXSTR]; scanf("%c", &ch); // 读取单个字符 scanf("\n"); // 消费换行符 scanf("%s", str); // 读取字符串 scanf("\n"); // 消费换行符 scanf("%[^\n]%*c", line); // 读取整行内容 printf("%c\n", ch); printf("%s\n", str); printf("%s\n", line); return 0; }
程序2代码
#include <stdio.h> #define MAXSTR 100 int main() { char ch; char str[MAXSTR]; char line[MAXSTR]; scanf("%c\n", &ch); scanf("%s\n", str); scanf("%[^\n]%*c", line); printf("%c\n", ch); printf("%s\n", str); printf("%s\n", line); return 0; }
测试用例输入
a hello world
(注:第三行开头有一个空格)
程序输出对比
程序1输出
a hello world
程序2输出
a hello world
差异原因分析
- 程序1逻辑:
读取ch后调用单独的scanf("\n")仅跳过当前换行;读取str后再次调用scanf("\n")也只跳过对应换行。最后%[^\n]会完整读取第三行的所有内容,包括开头的空格。 - 程序2逻辑:
scanf("%c\n", &ch)和scanf("%s\n", str)中的\n属于格式串的一部分,会匹配任意数量的空白字符(包括换行、空格)。读取str后,格式串中的\n会跳过第二行的换行,同时也会跳过第三行开头的空格,导致后续%[^\n]从'w'开始读取,最终line不含开头空格。
内容的提问来源于stack exchange,提问作者Lavya
相关产品推荐
相关产品推荐

