-
gets VS. scanf
Hello,
I know that in order to include a whitespace character in a string I need to use a gets() but it I can't input any charaters in before the program moves onto the next command asking for a an integer where I use a scanf to read that. Why does this happen and how can I fix it?
Thanks,
Vireyda
Code:
printf("\nPlease enter the following information:");
printf("\nEmployee %d Name: ", i);
gets(expenses[i].employee_name);
printf("\nEmployee Number: ");
scanf("%d", &expenses[i].emp_num);
-
>gets VS. scanf
Wow. That's really a question of which is worse. I would have to say gets because it can't be made safe while scanf can with a little effort.
>I need to use a gets()
No, you need to forget that gets exists and use fgets. Or, since this is C++, getline.
>Why does this happen
A previous call to scanf left a newline character in the stream. gets (or fgets, or getline) terminates upon reading a newline, so it appears as if the call was skipped.
>and how can I fix it?
Don't use scanf, or use scanf exclusively. Naturally the former is preferred. :) Also note that cin's >> operator works in much the same way as scanf, so you'll have similar problems. It's better to read all of your input as a string with fgets/getline and then extract the data you want with sscanf.