0

At the moment I have a bug so if I do not insert a number immediately, but a letter, the program goes in loop and does not ask me to insert a number again. Can you explain how to fix the problem?

int n, verify;

do{
    printf("I need a number now:\n);
    verify = scanf("%d", &n);
}while(verify != 1);
//after the first input if isn't a number i see the loop: "I need number now:\nI need number now:\nI need number now:\n..."

Resolved thanks to the indications in the comments.

User
  • 194
  • 2
  • 12
  • 1
    https://stackoverflow.com/questions/2023079/check-if-a-value-from-scanf-is-a-number – Jman Feb 08 '19 at 13:53
  • 2
    @PaulOgilvie The `"%d"` format skips leading white-space automatically. – Some programmer dude Feb 08 '19 at 13:54
  • 2
    There are multiple duplicates. The problem is that the wrong input is never removed from the input buffer. Use `fgets` and `sscanf` instead. – Some programmer dude Feb 08 '19 at 13:56
  • 3
    When `scanf` starts to read an integer, but reads an invalid character such as a letter, the invalid character will be pushed back onto the start of the stream and `scanf` will return the current item count (which will be 0 in your case). So effectively, the stream will be in exactly the same state before and after the call to `scanf`, leading to an infinite loop. – Ian Abbott Feb 08 '19 at 13:56
  • 2
    IMO the `scanf` family is unsuitable for user input. Use `fgets` instead and parse the input yourself or with `sscanf` – Jabberwocky Feb 08 '19 at 14:09
  • 1
    Thank you very much, I solved using sscanf, as recommended I copied the content from a string into a number, thus checking that it was really a number – User Feb 08 '19 at 14:36

0 Answers0