Thread: Read single words seperated by white space in as strings

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    34

    Read single words seperated by white space in as strings

    I am trying to read from a text file, and have each word become a new string. Is fgets a bad weapon of choice? It reads until a \n character, I guess I need to read until ' '?

    Code:
    LIST *CreateList(FILE *fp)
    {
       char buf[BUFSIZE];
    
       fgets(buf, 256, fp);
       puts (buf);
    
    
    } /* End CreateList */

  2. #2
    Registered User
    Join Date
    Sep 2009
    Posts
    36
    Quote Originally Posted by steals10304 View Post
    I am trying to read from a text file, and have each word become a new string. Is fgets a bad weapon of choice? It reads until a \n character, I guess I need to read until ' '?

    Code:
    LIST *CreateList(FILE *fp)
    {
       char buf[BUFSIZE];
    
       fgets(buf, 256, fp);
       puts (buf);
    
    
    } /* End CreateList */
    i think fgets automatically puts a null character at the end of the file.

    what if you tried

    Code:
    #define BUFSIZE 256
    
    char buf[BUFSIZE + 1];
    
    fgets(buf, BUFSIZE + 1, fp);
       
    puts (buf);

  3. #3
    Registered User
    Join Date
    Nov 2009
    Posts
    5
    Sure, use fgets to get the whole file/line. It is safe:

    From man-page
    fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or
    a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer

    then use strtok to get the words in separate strings.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strings and white space
    By ginom71 in forum C Programming
    Replies: 13
    Last Post: 07-12-2009, 09:48 AM
  2. Question of White space
    By terryrmcgowan in forum C Programming
    Replies: 3
    Last Post: 06-09-2003, 09:13 AM
  3. Help with Strings -- Please read
    By Drakkath in forum C++ Programming
    Replies: 6
    Last Post: 03-27-2002, 10:01 PM
  4. White space problems in file input
    By cxs00u in forum C++ Programming
    Replies: 4
    Last Post: 03-20-2002, 11:06 PM
  5. Galaxian or Space invaders for my next game (read this)
    By Leeman_s in forum C++ Programming
    Replies: 7
    Last Post: 11-07-2001, 09:28 PM