R
Robbie Brown
It's been many (many) years since I had to write a console application.
I want to be able to get a single integer from a console prompt.
I initially thought I needed to flush stdin when I had what I wanted but
this is apparently a big no no, so I hacked it.
I have the following code
int getChoice(){
int num = 0, choice = 0;
char c;
do{
printf("%s", "Enter an integer >> ");
num = scanf("%d", &choice);
while(c = getchar() != '\n');
}
while(num == 0);
return choice;
}
This code ignores characters and multiple integers and simply fetches
the first integer if there is one, embedded integers are ignored and
discarded, the only time an integer is returned is if it's the first
item in the stream.
What are your opinions of this code. This must be such a common
requirement that it has been solved countless times in the past.
I want to be able to get a single integer from a console prompt.
I initially thought I needed to flush stdin when I had what I wanted but
this is apparently a big no no, so I hacked it.
I have the following code
int getChoice(){
int num = 0, choice = 0;
char c;
do{
printf("%s", "Enter an integer >> ");
num = scanf("%d", &choice);
while(c = getchar() != '\n');
}
while(num == 0);
return choice;
}
This code ignores characters and multiple integers and simply fetches
the first integer if there is one, embedded integers are ignored and
discarded, the only time an integer is returned is if it's the first
item in the stream.
What are your opinions of this code. This must be such a common
requirement that it has been solved countless times in the past.