An assignment asks us to create a program in C that asks for user input of only numbers, using getchar() and infinite loop with while(1), that stops after typing a non-numeric character.

This is my attempt:

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

int main(){
    while(1){
        int x = getchar();
        if (isdigit(x) == 0){
            break;  
        };
    };
    return 0;
}

But when I run the code and type anything, it will stop after the first attempt, no matter what I type.

Can you please find a way to correct the code above?

1

There are 1 best solutions below

0
Allan Wind On

stdin is, by default, line buffered meaning the input will not be received by your program till you press <enter>. If you to entire newlines do something along these lines (pun):

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

int main(void) {
    for(;;) {
        int x = getchar();
        if(x == '\n')
            continue;
        if (!isdigit(x))
            break;
    }
}