问题描述
我有以下程序:
int main(int argc, char *argv[])
{
int a, b;
char c1, c2;
printf("Enter something: ");
scanf("%d",&a); // line 1
printf("Enter other something: ");
scanf("%d", &b); // line 2
printf("Enter a char: ");
scanf("%c",&c1); // line 3
printf("Enter another char: ");
scanf("%c", &c2); // line 4
printf("Done"); // line 5
system("PAUSE");
return 0;
}
正如我在C书上看到的,作者说scanf()
在缓冲区中留下了一个换行符,因此,程序不会停在第4行供用户输入数据,而是将换行符存储在 c2 中并移动到第 5 行.
As I read in the C book, the author says that scanf()
left a new line character in the buffer, therefore, the program does not stop at line 4 for user to enter the data, rather it stores the new line character in c2 and moves to line 5.
是吗?
然而,这是否只发生在 char
数据类型上?因为我没有看到第 1、2、3 行的 int
数据类型有这个问题.是吗?
However, does this only happen with char
data types? Because I did not see this problem with int
data types as in line 1, 2, 3. Is it right?
推荐答案
scanf()
函数在尝试解析字符以外的转换之前自动跳过前导空格.字符格式(主要是 %c
;还有扫描集 %[…]
— 和 %n
)是例外;他们不会跳过空格.
The scanf()
function skips leading whitespace automatically before trying to parse conversions other than characters. The character formats (primarily %c
; also scan sets %[…]
— and %n
) are the exception; they don't skip whitespace.
使用带有前导空格的 " %c"
跳过可选的空格.不要在 scanf()
格式字符串中使用尾随空格.
Use " %c"
with a leading blank to skip optional white space. Do not use a trailing blank in a scanf()
format string.
请注意,这仍然不会消耗输入流中留下的任何尾随空格,甚至不会消耗到行尾,因此如果还使用 getchar()
或 fgets()
在同一输入流上.我们只是让 scanf 在转换之前跳过空白,就像它对 %d
和其他非字符转换一样.
Note that this still doesn't consume any trailing whitespace left in the input stream, not even to the end of a line, so beware of that if also using getchar()
or fgets()
on the same input stream. We're just getting scanf to skip over whitespace before conversions, like it does for %d
and other non-character conversions.
注意非空白指令"(使用POSIX scanf术语) 除了转换,例如 scanf("order = %d", &order);
中的文字文本也不会跳过空格.文字 order
必须匹配要读取的下一个字符.
Note that non-whitespace "directives" (to use POSIX scanf terminology) other than conversions, like the literal text in scanf("order = %d", &order);
doesn't skip whitespace either. The literal order
has to match the next character to be read.
因此,如果您想从上一行跳过换行符但仍需要固定字符串的文字匹配,则您可能需要 " order = %d"
,喜欢这个问题.
So you probably want " order = %d"
there if you want to skip a newline from the previous line but still require a literal match on a fixed string, like this question.
这篇关于scanf() 将新行字符留在缓冲区中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!