Thread: gets VS. scanf

  1. #1
    Registered User Vireyda's Avatar
    Join Date
    Mar 2004
    Posts
    26

    Question 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);

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >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.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 08:35 AM
  2. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 04:39 PM
  3. Replies: 2
    Last Post: 02-20-2005, 01:48 PM
  4. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM