Undesired output when reading a file

Hi Guys,

I am reading from a file and printing the content on the console. But my output contains blank lines between each line of text.

i
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
nt main()
{
char buffer[500] ;
char i, j;
const char *a="love";
FILE *fp;

if ((fp = fopen("user.txt","r")) == NULL)
{
	 perror ("Error opening file");
}
     while ( !feof(fp))
   {
	// read in the line and make sure it was successful
	if (fgets(buffer,100,fp) != NULL)
	{
						
		       for(i = 0; buffer[i] != '\0'; ++i);

               for(j = 0; a[j] != '\0'; ++j, ++i)  
      	       {
                   buffer[i] = a[j];
     	        }
	    buffer[i] = '\0' ;
	    
	    cout << buffer << endl ;
     }  
   }
}


I am getting output like below

asharma5

as23w

qwssdd
Last edited on
Is there a reason you're using C-stdio functions to read your file instead of using C++ streams? If you were using C++ streams I doubt that you would be having these issues. By the way you really should avoid using eof() to control a read loop, use the actual read instead.

fgets() will treat the newline character as part of the line.
http://www.cplusplus.com/reference/cstdio/fgets/

1
2
3
4
5
6
7
8
9
10
11
12
13
        if (fgets(buffer,100,fp) != NULL)
        {
            // if last character is newline, replace with null
            int len = strlen(buffer);
            
            if (len > 0 && buffer[len-1] == '\n')
                buffer[len-1] = '\0';
            
            // add string to end of line
            strcat(buffer, a);

            cout << buffer << endl ;
        } 


or in C++ style
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{   
    ifstream fin ("user.txt");

    if (!fin)
    {
        perror ("Error opening file");
        return 1;
    }
    
    string buffer;
    const char *a = "love";
    
    while (getline(fin, buffer))
    {
        buffer += a;
        cout << buffer << endl ;  
    }
}
Last edited on
Topic archived. No new replies allowed.