Scanf returns 0 without waiting for input

sscanf
scanf not reading input
scanf not waiting for input
fgets
fscanf
scanf return value
scanf buffer
fgets not waiting for input

I have never programmed in C and today I have to write small code. Program is very easy - I want to add two integers. But when I'm trying to check if given input is a number and first scanf returns 0, the second one returns 0 too without waiting for input. Code:

int main()
{
    int a = 0;
    int b = 0;
    printf("Number a:\n");
    if (scanf("%d", &a) != 1)
    {
        printf("Not a number. a=0!\n");
        a = 0;
    }
    printf("Number b:\n");
    if (scanf("%d", &b) != 1)
    {
        printf("Not a number. b=0!\n");
        b = 0;
    }
    printf("%d\n", a+b);
    return 0;
}

That is because, once the first scanf() failed, it is probably because of matching failure, and the input which caused the matching failure, remains inside the input buffer, waiting to be consumed by next call.

Thus, the next call to scanf() also try to consume the same invalid input residing in the input buffer immediately, without waiting for the explicit external user input as the input buffer is not empty.

Solution: After the first input fails for scanf(), you have to clean up the input buffer, for a trivial example, something like while (getchar() != '\n'); should do the job.

How can I prevent scanf() to wait forever for an input character , Try using the select() function. Then you can wait for 10 seconds until you can read from stdin without blocking. If select() returns with zero,� “ Enter a number: 0 = 0x0 ” making the terminal locked out. Apparently scanf () returns without waiting for input. Debugging is impossible because when debug session stops at the breakpoint, there is no terminal communication with target whence no input possible and that means USB CDC firmware does not even start -nothing to debug.

The input that failed to convert to a number for the first fscanf() is still pending in standard input's buffer and causes the second fscanf() to fail as well. Try discarding offending input and re-prompting the user:

#include <stdio.h>

int main(void) {
    int a = 0;
    int b = 0;
    int c;
    printf("Number a:\n");
    while (scanf("%d", &a) != 1) {
        printf("Not a number, try again:\n");
        while ((c = getchar()) != EOF && c != '\n')
            continue;
        if (c == EOF)
            exit(1);
    }
    printf("Number b:\n");
    while (scanf("%d", &b) != 1) {
        printf("Not a number, try again:\n");
        while ((c = getchar()) != EOF && c != '\n')
            continue;
        if (c == EOF)
            exit(1);
    }
    printf("%d\n", a + b);
    return 0;
}

Factorizing the code with a utility function makes it much clearer:

#include <stdio.h>

int get_number(const char *prompt, int *valp) {
    printf("%s:\n", prompt);
    while (scanf("%d", valp) != 1) {
        printf("Not a number, try again:\n");
        while ((c = getchar()) != EOF && c != '\n')
            continue;
        if (c == EOF)
            return 0;
    }
    return 1;
}

int main(void) {
    int a, b;

    if (!get_number("Number a", &a) || !get_number("Number b", &b)) {
         return 1;
    }
    printf("%d\n", a + b);
    return 0;
}

A beginners' guide away from scanf() - palmen-it.de, Because scanf() returns how many items were converted successfully, the next This is because a string in C always needs a 0 byte appended to mark the end. just press enter, because scanf() is skipping it and continues to wait for input that can be matched. How would I get numbers without scanf() ? In this case, the first scanf won't find any number and will return 0. But it also won't read anything from the input. Because of this, the second scanf will see asd too. To clear the input if a isn't a number, you should input all remaining chars in the line until ' ' (look at the @Sourav's solution)

It's because of input and output aren't synchronized in C. The program can output some lines after user's input while the input hasn't been read. Try to run this code:

char token;

scanf("%c", &token);
printf("%c\n", token);
printf("line 1\n");

scanf("%c", &token);
printf("%c\n", token);
printf("line 2\n");

scanf("%c", &token);
printf("%c\n", token);
printf("line 3\n");

And input abc in one line.

You can imagine this like there are two separated consoles, one for input and another for output.


For example you want to input asd for a and 3 for b. In this case, the first scanf won't find any number and will return 0. But it also won't read anything from the input. Because of this, the second scanf will see asd too.

To clear the input if a isn't a number, you should input all remaining chars in the line until '\n' (look at the @Sourav's solution)

Caution when reading char with scanf (C), Usually, this happens inside a loop, but let's see a sample code without a loop that exposes the problem. printf ( "Input No.3\n" );. scanf ( "%c" , &c);. printf ( "c = %c\n" , c);. return 0; However, many would think now that, “Wait a minute… The scanf() function stops reading text input at the first white space character, space, tab, or Enter key. About the Book Author Dan Gookin wrote the original For Dummies book in 1991.

You could do the same thing using strings without problems with scanf. Just take the user input as string and convert it to integer. Then convert the string back to integer to check whether they are the same. If they are the same, treat a and b as integers, if not, do what you do (You will need to include string.h). Here is the working code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
int a;
int b;
char str1[100];
char str2[100];

printf("Number a:\n");  
scanf("%s", &str1); //take input as a string
a = atoi(str1); //convert string to integer
snprintf(str2, 100, "%d", a); //convert integer back to string

//if the integer converted to string is not the same as the string converted to integer
if (strcmp(str1, str2)!= 0)
{
printf("Not a number. a=0!\n");
a = 0;
}
printf("Number b:\n");
scanf("%s", &str1);
b = atoi(str1);
snprintf(str2, 100, "%d", b);

if (strcmp(str1, str2)!= 0)
{
printf("Not a number. b=0!\n");
b = 0;
}
printf("%d\n", a+b);

return(0);
}

String overflows with scanf, No matter how long your buffer is, a user could always supply input that is longer. &string2); printf ("\nYou typed the following string:\n%s\n", string2); return 0; } scanf call will gobble up all the remaining characters without even waiting for a� Return Submit 0 nothing the scanf will still be waiting for input. es on the this 1 point What number will be returned by the scanf function if the following code is run user types: Cheryl Popec (Cheryl Pope c followed by enter key) int main (void) { char firstname [6]; char lastname [ 6 ]; int favouriteNumber; int returnvalue = scanf ("%s %s %d" stname, lastname, &favouriteN Type your answer = 1570748 Return Submi nothing the scanf will still be waiting for input. tes on the r this umber

Function scanf, The next statement is scanf . scanf waits for the user to enter something. # include<stdio.h> int main() { int num =0; printf("Please type a number, some spaces, a second number, then It returns 1 because it has gotten 1 more input number! Input. 10 test. Output: x = 10, str = The problem with above code is scanf() reads an integer and leaves a newline character in buffer. So fgets() only reads newline and the string “test” is ignored by the program.

Basics of the scanf() Function in C Programming, The preceding scanf() statement waits for a floating-point value to be input, scanf("%s",firstname); printf("Pleased to meet you, %s.n",firstname); return(0); }. I'm a C n00b. I have a simple question, how do you get "scanf" (or an equivalent) that doesn't wait for the user's input (or waits a specific amount of time)? What I want to do is simple. I want my program to print numbers 1 to 5 and 4 to 1 while waiting 1 second / the current number (e.g. 0.2 seconds for the number 5).

C program to read string with spaces using scanf() function , Output -1 (Enter name without space) The age input was successful but compiler doesn't wait to read name and moves to next statement which was name: "); scanf("%[^\n]",name); printf("Name is: %d, age is: %d\n",name[0],age); return 0; }.

Comments
  • UV for checking the return value of the input function ... != 1. Far too many problems stem from not doing that first step. At least this post did that important step.
  • May want to check for newlines as well.
  • You need a bit more complex while loop, best wrapped in a function. Reading until EOF doesn't stop reading when input buffer is empty, it will block. It will only end at EOF, which means user entered ctrl-d (Unix shell) or ctrl-Z (Windows terminal) or something like that.
  • @hyde yes, basically you're correct, i just wanted to portray the idea, that's all.
  • Thanks for your help! Version with EOF just stucked the program, but this with '\n' works!