-
Loop reading input
Hi everyone,
At first, pls excuse my bad english, hope u can understand what i mean.
im trying to write a function doing the following:
- loop asking for user input, which should be a unsigned long (e.g.: 1234543,123131,12,123144)
- that input MUST only be numbers and no other characters, the length of the input cannot be determined BEFORE the input
- if the input is empty or consists of anything else but only numbers, i have to write an error msg
- after that error msg, i have to ask again for the input
i am trying to do this for hours, but i constantly get errors.
At first, i tryed it with a scanf in the loop, but apparently scanf cant ask for user input in a loop
Has anyone some tips or ideas how I can do it?
-
Please post your attempt.
-
Code:
#include <stdio.h>
int main()
{
unsigned long user_input = 0;
unsigned long tmp = 0;
printf("\nid? ");
tmp = scanf("%ld", &user_input);
while (tmp != 1)
{
printf("wrong id, please enter a new one");
printf("\nid? ");
tmp = scanf("%ld", &user_input);
}
//printf("\n%ld\n", user_input);
//printf("%ld", tmp);
return 0;
}
-
scanf format specifier for unsigned long is %lu.
Btw, don't declare tmp as unsigned. since scanf() may return EOF(negative value) .
-
applied your changes (ld -> lu, tmp is now long)
still infinite loop when i enter anything BUT numbers
-
As you've probably noticed, input like "1f" will be accepted just fine by what you have. That's both the good thing and the bad thing about scanf: it will try to match what it can to the input, and as long as something matches, then you'll get a result.
If you want to consider the whole thing they type in, then you'll need to make sure you get all the input. You can either read in the whole line, and then verify the input; or you can read in a character at a time and process as you go.