1

I've been learning C for a while now and I've run into a problem with asking the user for input that has to meet some requirements. What I want to happen is when the input is the wrong ex. The input is not a number but a character, I want it to loop until the data is correct. My code:

#include <stdio.h>
int main() {
    int c;
    int number;
    printf("Insert your number: ");
    while (scanf_s("%d", &number) != 1 || getchar() != "\n" || number <= 0) {
        printf("Wrong input. Insert again: ");
        while ((c = getchar()) != '\n' && c != EOF);
    }
    printf("Your number is %d.", number);
    printf("\n\nEnd of the program\n\n");
    return 0;
}

Now the program reads all the input as incorrect and is stuck in an infinite loop. Any suggestions?

Veanty
  • 33
  • 5
  • does the program prompt you to enter input and after you write it and enter it it loops, or it loops when you execute it without prompting? – emetsipe Nov 13 '22 at 14:47
  • 3
    Does this answer your question? [Validate the type of input in a do-while loop C](https://stackoverflow.com/questions/31633005/validate-the-type-of-input-in-a-do-while-loop-c) – Andreas Wenzel Nov 13 '22 at 14:48
  • 1
    Don't use `scanf`. It's more trouble than it's worth. Read a full line, as a string, using `fgets`. Validate it however you wish, perhaps using `sscanf`. If it's no good, loop and prompt the user to try again. See [What can I use for input conversion instead of `scanf`?](https://stackoverflow.com/questions/58403537) – Steve Summit Nov 13 '22 at 14:52

0 Answers0