0

I Was Working On Small Program In C Language. It Should Get How Many Hours User Has Worked In A Week(Input) Then Display Salary(output) Based On It. Problem Is That I Want To Make Infinite Loop To Make Sure That User Write Numbers Only In Input Like This:

int hours;

// get input
while(1)
{
    printf("How Many Hours You Worked This Week: ");
    
    if(scanf("%u", &hours))
        break;
    else
        printf("oops, Write Integers Only not string or chars\n");
}

But Problem Is That When User Write Wrong Input It Execute Else And Then Repeat Loop, But It Doesn't Stop To Ask For Input Again! It Just Keep Repeating. I Think It Is Problem With \n char And Scanf (I Always Have Problem With This Func :)). I Will Be Happy If You Help!

  • 3
    "Problem with scanf" is a truism. – William Pursell Aug 23 '21 at 21:36
  • If there is an invalid character in the input stream, `scanf` will not consume it. Since you're in a loop, it will continue to try (and fail) to read that character. As a simple hack, try `fprintf(stderr, "oops\n"); getchar();` to consume at least one character on each iteration of the loop. – William Pursell Aug 23 '21 at 21:38
  • 2
    `scanf` is terrible for reading in uncontrolled input (and arguably terrible in general). Input that is not matched remains in the input stream. Use something like `fgets` to consume the input and then `sscanf` to attempt to parse it. – kaylum Aug 23 '21 at 21:38
  • The easy solution to this problem — this will sound like a terrible cop-out, but I mean it — is "don't worry about it". Tell the users of your program that when they're supposed to type numeric input, they *must* type numeric input, and that if they don't, the program will misbehave. – Steve Summit Aug 23 '21 at 21:40
  • Of course it's possible to write a program that enforces numeric input, that prints something like "please try again" when the user fails, but *it is not reasonable to build such a a program around `scanf`*. `scanf` is simply not up to the job. – Steve Summit Aug 23 '21 at 21:40

0 Answers0