white space in format string of scanf() [duplicate]

荒凉一梦 提交于 2020-01-15 11:47:52

问题


#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 ;
}

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 ...


回答1:


If you give a space after your numbers, scanf must determine the end of the whitespaces to be matched:

scanf("%d ", &a);

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
........

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.

If you call scanf("%d ") instead, the leftover stream is

2
.

You see the whitespaces are gone immediately.




回答2:


Take a look at this.

You can use a space between the %d's. That will require from the user to input something like: 12 32 (with the spaces).

If you don't want that, you should use a loop with the scanf.

Good luck.



来源:https://stackoverflow.com/questions/47903523/white-space-in-format-string-of-scanf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!