【发布时间】:2021-11-29 17:38:08
【问题描述】:
#include <stdio.h>
#include <string.h>
#include<stdio.h>
int main()
{
int ch;
char str;
scanf("%d", &ch);
scanf("%c", &str);
printf("x = %d, str = %c", ch, str);
return 0;
}
输入:10(输入)
输出:x = 10,str =
在这段代码中 scanf("%d", &ch); 读取一个整数并在缓冲区中留下一个换行符。所以 scanf("%c", &str); 只读取一个换行符。 我明白了。
但是当我运行这段代码时:
#include <stdio.h>
#include <string.h>
#include<stdio.h>
int main()
{
int ch;
char str[54];
scanf("%d", &ch);
scanf("%s",str);
printf("x = %d, str = %s", ch, str);
return 0;
}
输入:10(enter) test
输出:x = 10, str = test
这里似乎 scanf("%s",str); 忽略了缓冲区中的换行符并从控制台读取 test。
为什么会这样?
【问题讨论】:
-
欢迎来到 Stack Overflow。请通过tour 了解 Stack Overflow 的工作原理,并阅读How to Ask 了解如何提高问题的质量。 Please do not upload images of code/errors when asking a question.
-
它会跳过换行符按设计。
scanf转换在它无法转换的第一个字符处停止,通常(但不一定)是空格或换行符,并且该字符保留在输入缓冲区中。 nextscanf()将读取它。格式说明符%d和%s和%f会自动过滤这些前导空白字符,但%c和%[]和%n不会。您可以通过在%之前添加一个空格来指示scanf这样做。 -
大多数
scanf格式字符在解析前 跳过前导空格。并且所有scanf格式字符在解析后都会留下尾随空格(如换行符\n)。所以通常后面的\n会被下一个scanf调用处理。但与其他人不同的是,"%c"确实 not 跳过前导空格 - 因此它将前一个调用中的尾随\n作为它读取的字符。如果你想让"%c"表现得像其他人一样,你可以输入一个明确的空格,像这样:" %c"。