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

This is a discussion on help with fgets !!!!!!!!!! within the C Programming forums, part of the General Programming Boards category; let say if i have something like this Code: typedef struct { char states[50]; char cities[50]; int tempt; } INFO; ...

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    48

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

    let say if i have something like this
    Code:
    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
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    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 08:26 PM.

  3. #3
    Registered User
    Join Date
    Apr 2011
    Location
    Las Vegas
    Posts
    66
    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:

    Code:
    #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 08: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, 09:36 AM
  2. using fgets()
    By rambos in forum C Programming
    Replies: 5
    Last Post: 05-05-2008, 12:39 AM
  3. Concerning gets() and fgets()
    By ozumsafa in forum C Programming
    Replies: 20
    Last Post: 07-19-2007, 06:32 AM
  4. fgets
    By Axel in forum C Programming
    Replies: 16
    Last Post: 09-15-2006, 12:09 PM
  5. fgets
    By ylph02 in forum C Programming
    Replies: 1
    Last Post: 06-05-2002, 11:24 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21