scanf()格式字符串中的空白 [英] white space in format string of scanf()
问题描述
#include<stdio.h>
int main() {
int a,b;
printf("Enter values of a and b\n");
scanf(" %d%d ",&a,&b);
printf("a=%d b=%d", a, b);
return 0 ;
}
在这里,如果我使用scanf(),如我的代码中所示,则编译器期望用户输入三个值,而我在不带任何空格的情况下使用scanf()时,它仅要求两个输入,我无法理解不出所料,所以我很困惑这两者之间的区别,请解释...
Here if I use scanf(), as in my code then the compiler expects the user to enter three values, I am unable to understand this , when i use scanf() without any white space then it asks for only two inputs as expected , so i am confused whats the difference between these two , plz explain ...
推荐答案
如果在数字后留一个空格,则scanf
必须确定要匹配的空格的结尾:
If you give a space after your numbers, scanf
must determine the end of the whitespaces to be matched:
scanf("%d ", &a);
此处的空格表示读取并丢弃所有空格. scanf
必须出现非空白字符(或EOF),以清楚地说明 all 是什么,以便可以正确读取和丢弃它们.
Here the space means read and discard all whitespaces. A non-whitespace character (or EOF) must appear for scanf
to make it clear what all is so they can be properly read and discarded.
考虑此输入流(点是字符指示符):
Consider this input stream (dots are character indicators):
1 2
........
如果您呼叫scanf("%d")
,则在呼叫后,剩余的流为
If you call scanf("%d")
, then after calling, the leftover stream is
2
....
...,在下一次读取时将丢弃空格.请注意,读取数字时,前导空格会被自动丢弃.
... where the whitespaces will be discarded at next read. Note the leading spaces are automatically discarded when reading the number.
如果您呼叫scanf("%d ")
,则剩余的流为
If you call scanf("%d ")
instead, the leftover stream is
2
.
您看到空格立即消失了.
You see the whitespaces are gone immediately.
这篇关于scanf()格式字符串中的空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!