击中返回将终止2 scanf(“%[^ \ n]%* c”)

时间:2019-09-20 18:46:54

标签: c string scanf c99

我正在尝试读取2行用户输入。对于第一个序列,如果我什么也没输入,只是按回车键,程序将打印enter the second sequence,但不允许第二个scanf。基本上,返回仅终止两个scanf,导致str1str2都为空。

printf("enter the first sequence: ");
scanf("%[^\n]%*c", str1);

printf("enter the second sequence: ");
scanf("%[^\n]%*c", str2);

有什么办法可以解决这个问题?

1 个答案:

答案 0 :(得分:3)

字符串的格式说明符为%s,因此请改用它:

printf("enter the first sequence: ");
scanf("\n%s", str1);

printf("enter the second sequence: ");
scanf("\n%s", str2);

正如@AjayBrahmakshatriya所说:\n可以匹配任意数量的\n个字符。

使用scanf读取char时,%c的问题在于它将换行符视为输入,正如我在此example中所解释的那样。


但是,如果我是你,我只会使用fgets(),就像这样:

fgets(str1, sizeof(str1), stdin);
fgets(str2, sizeof(str2), stdin);

如果您采用这种方法,那么您可能会对Removing trailing newline character from fgets() input感兴趣吗?