Thread: Can someone help me fix my code! Thank you!

  1. #1
    Registered User arti's Avatar
    Join Date
    May 2010
    Posts
    108

    Can someone help me fix my code! Thank you!

    I'm reading from the data file and it prints out with like so:
    Code:
    **************************************
    
    *                                             *
    My code is printed below....I can't have the spaces and i thought that NULL was supposed to eliminate the blankline. What am I doing wrong? If I use printf after fgets i get garbage and sometimes errors that i cannot convert char to char.
    Code:
    if(fgets(line, MAXLINE, inputFILE)!=NULL)
        puts(line);
     if(fgets(line, MAXLINE, inputFILE)!=NULL)
        puts(line); 
     if(fgets(line, MAXLINE, inputFILE)!=NULL)
        puts(line);

  2. #2
    Registered User
    Join Date
    Jun 2009
    Posts
    120
    fgets returns NULL only if a read error occurs or end of file is reached. 'Blank' line (that is line containing only new-line character) is still valid for fgets. You need to check characters in your line buffer. Line could be terminated with \n or \r\n.

    EDIT:
    puts appends new-line character at end of the string so you end up with 2 new-line characters resulting in displaying 'blank' line. Use printf instead.
    Code:
    if (fgets(line, MAXLINE, inputFILE) != NULL && line[0] != '\r' && line[0] != '\n')
    {
        printf("%s", line);
    }
    Last edited by DRK; 05-16-2013 at 03:09 AM.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by DRK View Post
    puts appends new-line character at end of the string so you end up with 2 new-line characters resulting in displaying 'blank' line. Use printf instead.
    If would be easier to use fputs() instead - as that does not append a newline.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 09-19-2012, 01:58 PM
  2. Replies: 1
    Last Post: 03-10-2010, 11:28 AM
  3. Replies: 14
    Last Post: 04-01-2008, 02:23 AM
  4. producing c/c++ code from flowcharts,pseudo code , algorithims
    By rohit83.ken in forum C++ Programming
    Replies: 3
    Last Post: 02-20-2008, 07:09 AM
  5. Having trouble translating psudeo-code to real-code.
    By Lithorien in forum C++ Programming
    Replies: 13
    Last Post: 10-05-2004, 07:51 PM