0

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?

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • OT: Semicolon `;` is only needed after non-block statements. After `{}` blocks it's considered an empty statement. – Some programmer dude Apr 28 '23 at 04:29
  • As for your problem, what do you think happens with the newline that the `Enter` key is adding to the input buffer? The lesson for today: Learn how to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your programs. Like using a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through your code line by line while monitoring variables and their values. – Some programmer dude Apr 28 '23 at 04:29
  • 1
    "it will stop after the first attempt" No, it will not. Add `printf("%d\n", x);` just after `getchar` and give the input `123` and you'll see that the loop executes 4 times – Support Ukraine Apr 28 '23 at 05:17
  • In other words... the program is doing exactly what your description says. But perhaps the description is missing something like: "only numbers and newlines" – Support Ukraine Apr 28 '23 at 05:24

1 Answers1

0

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;
    }
}
Allan Wind
  • 23,068
  • 5
  • 28
  • 38