Input reading using scanf hangs

2019-03-03 19:47发布

I am programming in C and i have a problem when i run a program in the cmd terminal. here is the code i use:

#include <stdio.h>

int main() {

    int num;

    printf("enter a number: ");
    scanf("%i\n", &num);

    for(int n = 1; n < num + 1; n++){
        printf("%i\n", n);
    }


    return 0;
}

Generally, everything works like it should, exept for one thing. when I enter a number, nothing happens. there is no output, until I write anything and press Enter, and only then the number appear.

this is a screenshot of what it looks like. here is enter the number (and press enter) but nothing happens: http://prntscr.com/deum9a

and this is how it looks like after i entered something random nad all the numbers popped up: http://prntscr.com/deumyn

if anyone knows how to fix this, please tell me (:

标签: c scanf
1条回答
时光不老,我们不散
2楼-- · 2019-03-03 20:02

Remove the \n from scanf()

scanf("%i", &num);

When you have a whitespace character in the format string, scanf() will ignore any number of whtiespaces you input and thus the ENTER you do doesn't terminate the input reading. Basically, you'll be forced to input a non whitespace character again in order complete the scanf() call.

Generally, scanf() is considered bad for input reading. So, considering using fgets() and parsing the input using sscanf().

See: Why does everyone say not to use scanf? What should I use instead?

查看更多
登录 后发表回答