Thread: gets(); problems

  1. #1
    NeillH
    Guest

    Unhappy gets(); problems

    I am a fairly new C programmer and am having trouble using
    gets().

    I am using it to get values for structure members from keyboard input (not sure if this is important or not) The actual problem is that when executing, the first gets() statement is ignored, unless I put two statements together.

    For example:

    printf("Enter Make and Model: ");
    gets(car[rec_num].make_model);

    Becomes

    printf("Enter Make and Model: ");
    gets(car[rec_num].make_model);
    gets(car[rec_num].make_model);

    Can anyone shed any light as to why this is happening.

    I am using Borland C++ Builder to compile my programs (Again not sure if that important but hey...)

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    First, don't use gets. There's a safer version of gets called fgets, second, the problem is probably caused by a scanf earlier in the program. It reads some input but leaves a newline character in the input stream and gets will read just the newline, causing you to need two calls to gets. Try this:
    printf("Enter Make and Model: ");
    while ( getchar() != '\n' );
    fgets(car[rec_num].make_model, sizeof car[rec_num].make_model, stdin );

    -Prelude
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    197
    Hi!
    I had the same problem. Donīt use scanf() and gets() if possible!

    klausi
    When I close my eyes nobody can see me...

  4. #4
    Mister X
    Guest
    is it possible to use fgets on ex.a buffer
    if:
    char buffer[30]; /* here we have some data, text */

    fgets(car[rec_num],sizeof car[rec_num]. buffer);

    Mx.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >is it possible to use fgets on ex.a buffer
    No, fgets will only read from a FILE *. To read data from a string use sscanf, for example:
    sscanf ( buffer, "%s", car[rec_num].data );

    The conversion flags are the same as scanf, and you have to be just as careful not to overflow the variables you are reading to.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. No clue how to make a code to solve problems!
    By ctnzn in forum C Programming
    Replies: 8
    Last Post: 10-16-2008, 02:59 AM
  2. C Pointers Problems
    By mhelal in forum C Programming
    Replies: 8
    Last Post: 01-10-2007, 06:35 AM
  3. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  4. contest problems on my site
    By DavidP in forum Contests Board
    Replies: 4
    Last Post: 01-10-2004, 09:19 PM
  5. DJGPP problems
    By stormswift in forum C Programming
    Replies: 2
    Last Post: 02-26-2002, 04:35 PM