Can someone help me fix my code! Thank you!

This is a discussion on Can someone help me fix my code! Thank you! within the C Programming forums, part of the General Programming Boards category; I'm reading from the data file and it prints out with like so: Code: ************************************** * * My code is ...

  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
    DRK
    DRK is offline
    Registered User
    Join Date
    Jun 2009
    Posts
    107
    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,208
    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%.

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, 10: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, 06: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

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