Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

Why scanf("%d", [...]) does not consume ' '? while scanf("%c") does?

Here, I saw this statement in the accepted answer:

Most of the conversion specifiers skip leading whitespace including newlines but %c does not.

For me it is not clear the rationale under this different behaviors, I would have expected a uniform one (e.g. always skipping or never).

I came into this kind of problem with a piece of C code like this:

#include "stdio.h"

int main(void){

    char ch;
    int actualNum;

    printf("Insert a number: ");
    scanf("%d", &actualNum);
    // getchar();

    printf("Insert a character: ");
    scanf("%c", &ch);

    return 0;
}

Swapping the two scanfs solves the problem, as well as the (commented) getchar, otherwise the ' ' of the first insertion would be consumed by the second scanf with %c. I tested on gcc both on linux and windows, the behavior is the same:

gcc (GCC) 4.7.2 20120921 (Red Hat 4.7.2-2)
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

So my question is: Why does %d and %c behave differently w.r.t. ' ' in scanf?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is consistent behavior, you're just thinking about it wrong. ;)

scanf("%c", some_char); // reads a character from the key board.
scanf("%d", some_int);  // reads an integer from the key board.

So if I do this:

printf("Insert a character: ");
scanf("%c", &ch);                // if I enter 'f'. Really I entered 'f' + '
'
                                 // scanf read the first char and left the '
'
printf("Insert a number: ");
scanf("%d", &actualNum);      // Now scan if is looking for an int, it sees the '
'
                              // still, but that's not an int so it waits for the 
                              // the next input from stdin

It's not that it's consuming the newline on its own in this case. Try this instead:

char ch;
char ch2;
printf("Insert a character: ");
scanf("%c", &ch);
printf("Insert another character: ");
scanf("%c", &ch2); 

It will "skip" the second scanf() because it reads in the ' ' at that time. scanf() is consistent and you MUST consume that ' ' if you're going to use it correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...