Thread: help with fgets !!!!!!!!!!

  1. #1
    Registered User
    Join Date
    Apr 2011

    help with fgets !!!!!!!!!!

    let say if i have something like this
    typedef struct
    	char states[50];
    	char cities[50];
    	int tempt;
    } INFO;
    there are 2 string in the struct how would i use fgets to read both string at the same time, i know how to read single string using fgets

  2. #2
    Join Date
    Aug 2010
    Ontario Canada
    Use scanf()...

    And lose the stupid exclamation marks... 'round here that has exactly the opposite of the desired effect.

    edit: should have been "Use fscanf() " ... sorry.
    Last edited by CommonTater; 04-18-2011 at 07:26 PM.

  3. #3
    Registered User
    Join Date
    Apr 2011
    Las Vegas
    You can use scanf, but it will stop scanning when it reaches a whitespace character. This would be a detriment if you have a state or city name with a space (e.g. "Las Vegas"). fgets is the safer form of gets, as it allows you to specify a maximum number of characters to read. So, to answer your question, take a look at the following:

    #include <stdio.h>
    #define MAX 50
    typedef struct {
        char states[MAX];
        char cities[MAX];
        int tempt;
    } Info_t;
    int main( void )
        Info_t info;
        fgets( info.states, MAX, stdin );
        fgets( info.cities, MAX, stdin );
        scanf( "%d", &info.tempt );
        return 0;
    Note the use of a #define preprocessor macro to set the number of characters to be read - this makes it easy to propagate changes throughout your code.

    Be aware that fgets will retain a newline character, if present. You may need to make accommodations for this in your code.
    Last edited by kmess; 04-18-2011 at 07:25 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. help with fgets
    By n3cr0_l0rd in forum C++ Programming
    Replies: 25
    Last Post: 06-10-2009, 08:36 AM
  2. using fgets()
    By rambos in forum C Programming
    Replies: 5
    Last Post: 05-04-2008, 11:39 PM
  3. Concerning gets() and fgets()
    By ozumsafa in forum C Programming
    Replies: 20
    Last Post: 07-19-2007, 05:32 AM
  4. fgets
    By Axel in forum C Programming
    Replies: 16
    Last Post: 09-15-2006, 11:09 AM
  5. fgets
    By ylph02 in forum C Programming
    Replies: 1
    Last Post: 06-05-2002, 10:24 PM