Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fgets( ) and odd behavior

Status
Not open for further replies.

ezeke1

Programmer
Mar 20, 2003
41
US
Hello All,
I'm experiencing some odd runtime behavior when using the fgets() function as an alternative to scanf(). I'm simply trying to read in some user input such as a string of text. I notice that if I use the fgets() call inside the main() routine, I get a user prompt. But if I call fgets() from a subroutine function, the program doesn't prompt for any user input. Does anyone know what the issue is?

David
 
Yes, you're mixing fgets() calls with scanf() calls.

Calling scanf() before fgets() almost always results in scanf() leaving an unused newline on the input stream, which is exactly what fgets() is looking out for.

I just stick to using fgets() for ALL input, then using sscanf() (or whatever else seems appropriate) for dealing with the resulting buffer of input.

--
 
Thank you for the attention Salem. You are right, I used scanf in an earlier section of my program because I needed to read in an integer and not a whole line. If I have to mix scanf and fgets, is it possible to flush the input buffer to solve the problem? Can I mix fgetc calls with fgets?

David
 
Sure you can - but its no better or easier than replacing all your scanf calls with a fgets() and sscanf() combination.



--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top