lovecreatesbeauty said:
[color=blue]
> /*
> When should we worry about the unwanted chars in input stream?[/color]
When you know they're unwanted.
[color=blue]
> Can we
> predicate this kind of behavior and prevent it before debugging and
> testing? What's the guideline for dealing with it?[/color]
Decide what you wish to keep and what you wish to discard. Devise an
algorithm for distinguishing between them. Implement the algorithm.
[color=blue]
> As shown below line #21, I should remove the unwanted characters in
> input stream there at that time. Do I miss some other possible errors
> in i/o which will happen to occur sometimes in other places? And
> welcome your kind comments on following the code, thank you.
> */
>
>
> 1 #define STRLEN 200
> 2
> 3 int main(int argc, char *argv[])[/color]
Well done, you got main() right. A good start.
[color=blue]
> 4 {
> 5 int ret = 0;
> 6 char cust[STRLEN] = {'\0'};
> 7 char dest[STRLEN] = {'\0'};
> 8 char flight = '\0';
> 9 char hotel = '\0';
> 10
> 11 printf("Customer name: ");[/color]
Undefined behaviour. You forgot to #include <stdio.h>
[color=blue]
> 12 gets(cust);[/color]
Never, ever, ever, ever, ever, ever, ever use gets(). Use fgets instead, as
it allows you to specify how much storage space you have available for the
input. Any input that won't fit will stay in the stream awaiting collection
by the next function to read from that stream.
[color=blue]
> 13 printf("Destination: ");
> 14 gets(dest);[/color]
Never, ever, ever, ever, ever, ever, ever use gets(). Use fgets instead, as
it allows you to specify how much storage space you have available for the
input. Any input that won't fit will stay in the stream awaiting collection
by the next function to read from that stream.
[color=blue]
> 15
> 16 printf("Will flight be available: ");
> 17 flight = getchar();[/color]
Why not use fgets here too?
[color=blue]
> 18 printf("Will hotel be available: ");
> 19
> 20 /* remove unwanted chars in input stream here now */
> 21 while(getchar() != '\n'); //intended null loop body[/color]
This won't work, because it will keep reading and discarding characters up
to AND INCLUDING the first non-newline, which is presumably supposed to be
data.
I suggest capturing all your data in string form, using fgets (for now, that
is - later you'll probably devise your own input routine when you have a
lot more experience), even if it's single-character data. It's easy enough
to pick a single character out of a string if that's all you need from it.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)