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
1.6k views
in Technique[技术] by (71.8m points)

c - 'printf' followed by 'scanf' requires pressing ENTER key twice to accept input

I'm a complete beginner in C programming and I have a question. I'll bring a simple code as an example:

#include <stdio.h>

int main( void )
{
    int x;
    printf( "Please type the number 10." );
    scanf( "%i
", &x );

    if ( x == 10 )
        printf( "Thank you!
" );


    return 0;
}

As expected, when I compile and run this program, my terminal displays the message:

"Please type the number 10."

Then it waits for input, so I type the number it asks for (10), and press ENTER. The problem is that after I press ENTER once, it moves to a new line and waits for more input. Only after typing 10 and pressing ENTER again does it actually move on (... to display "Thank you!").

So it appears that I have to press ENTER twice for my input to be accepted. Does anyone know why this happens?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It's the " " in your call to scanf. Remove that and scanf will return after scanning the integer value you requested.

Note: This has nothing to do with the fact that the scanf call is preceded by a printf.


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

...