Cheang Wai Bin
Cheang Wai Bin

Reputation: 191

How to validate the input type to receive integer only?

I only want to receive integer from the user and I tried doing as the code below but it doesn't seems to be quite right.

int num;

printf("What is the ID?\n>> ");
        while(!scanf("%d", &num)){
            // consume new line
            getchar();
            printf("\nInvalid ID please try again...\n\n");
            printf("What is the ID?\n>> ");
        }

If I only input a into the scanf, it works fine, but when I input ab into the scanf, it loops 2 times and if i input 3 alphabet it will loops 3 times. Why is it?

What is the ID?
>> a

Invalid ID please try again...

What is the ID?
>> abc

Invalid ID please try again...

What is the ID?
>>
Invalid ID please try again...

What is the ID?
>>
Invalid ID please try again...

What is the ID?
>>

Upvotes: 0

Views: 38

Answers (2)

chux
chux

Reputation: 154218

Code needs to consume the non-numeric line of input.

Various ways to read the rest of the line

int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
  ;
}

Or

scanf("%*[^\n]");  // read all non- \n
scanf("%*1[\n]");  // read 1 \n

Avoid below. Fails to read anything when the next character is a '\n'.

scanf("%*[^\n]%*c");

Upvotes: 1

Lyon
Lyon

Reputation: 272

#include <stdio.h>

int main(void) {
int num;
char c;
printf("What is the ID?\n>> ");
    while(!scanf("%d", &num)){
        // consume new line
        gets(&c);
        printf("\nInvalid ID please try again...\n\n");
        printf("What is the ID?\n>> ");
    }
return 0;
}

By adding a gets() you can take in the new line and remove the issue.

Upvotes: 0

Related Questions