oron
oron

Reputation: 23

scanf taking int but continues execution only after entering another char/int and pressing enter

In my code (in c) scanf() takes one integer value but when I type an integer and press enter then nothing happens (the execution do not continue as it should). I need to press on a key and only then the program continue with the number I did press first.

example: code:

int num=0;
printf("Enter a number and see if he belong to one of the groups:");
scanf("%d\n\n",&num);

Output:

Enter a number and see if he belong to one of the groups:5(enter) 

f(enter)

and only then the code continues....

Upvotes: 0

Views: 604

Answers (2)

chux
chux

Reputation: 153367

If accepted solution of

scanf("%d\n", &num);

works differently than your posted code, you have a non-compliant compiler. The whitespace after the "%d", if "\n", "\t", " " or others as well as the number of them should make no difference. They all consume 0 or more following whitespace(s). scanf("%d\n", &num) does not return until a non-whitespace (or EOF) is entered.

As @pepo suggests, use

scanf("%d", &num);

or better yet, use fgets()/sscanf().

Upvotes: 1

user1019830
user1019830

Reputation:

Well, it seems that you are telling scanf to read two newline characters, not one:

scanf("%d\n\n", &num);

This should give the right behaviour instead:

scanf("%d\n", &num);

Upvotes: 1

Related Questions