I want the code to run until the user enters an integer value.
The code works for char
and char
arrays.
I have done the following:
#include <stdio.h>
int main()
{
int n;
printf("Please enter an integer: ");
while(scanf("%d",&n) != 1)
{
printf("Please enter an integer: ");
while(getchar() != '\n');
}
printf("You entered: %d\n",n);
return 0;
}
The problem is if the user inputs a float value scanf
will accept it.
Please enter an integer: abcd
Please enter an integer: a
Please enter an integer: 5.9
You entered: 5
How can that be avoided?
scanf()
.fgets()
to get an entire line.strtol()
to parse the line as an integer, checking if it consumed the entire line.char *end;
char buf[LINE_MAX];
do {
if (!fgets(buf, sizeof buf, stdin))
break;
// remove \n
buf[strlen(buf) - 1] = 0;
int n = strtol(buf, &end, 10);
} while (end != buf + strlen(buf));
Use fgets
and strtol
,
A pointer to the first character following the integer representation in s
is stored in the object pointed by p
, if *p
is different to \n
then you have a bad input.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *p, s[100];
long n;
while (fgets(s, sizeof(s), stdin)) {
n = strtol(s, &p, 10);
if (p == s || *p != '\n') {
printf("Please enter an integer: ");
} else break;
}
printf("You entered: %ld\n", n);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With