Hi there,
Quote:
Originally Posted by atlantis43
I'm wondering if someone can explain why I have to hit ENTER twice if using the scanf() code line, but only once when using sscanf()code line in the following code.
|
that's because scanf() reads input from stdin, while sscanf() reads from a string. This means that scanf() replaces fgets()
and sscanf(). If you leave fgets() and still use scanf(), as your code shows ...
Code:
printf("Enter phone number for worker\n");
fgets(phone, sizeof(phone), stdin);
scanf("%s", &phone);
//sscanf(phone,"%s", &phone);
printf("phone# is %s\n", phone);
.. then what happens is this:
First fgets() reads a line from stdin and stores it in phone. That needs pressing the ENTER key once to finish the input
Then scanf attempts to read a second line of input from stdin. If you don't enter anything, but just hit ENTER again, tha previous value stored in phone remains unchanged. However, if you enter at least one character before the second ENTER, this will be your new input you receive in phone.
I strongly recommend the combination of fgets() and sscanf(), because that way you can prevent buffer overflows. Using scanf() only, you'll get a buffer overflow if the actual input is longer than the buffer you reserved for it, because there is no length check (AFAIK even scanf("%10s", ...) isn't safe, but I'm not absolutely sure about that). The result can be anything from unpredictable behavior to a segmentation fault.
[X] Doc CPU