Reading Lines form file problum
Apr 23, 2011 at 6:39pm UTC
Hi i am trying to make a little program to execute commands
My problum is when I read in a file for example like the one below
at the end it adds an extra line
1 2 3
SET A,"Hello World"
PAUSE
Echo A
So this is the code I use to read the above lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
#include <iostream>
using namespace std;
int main(){
FILE *fp;
char buffer[50];
fp = fopen("C:\\out\\test.txt" ,"r" );
if (fp == NULL){
cout << "Cannot Open Filename\n" ;
return 0;
}
while (!feof(fp)){
fgets(buffer,50,fp);
//Write out each line
cout << buffer;
}
system("pause" );
}
After running the code in the console it adds an extra line like below:
1 2 3 4
SET A,"Hello World"
PAUSE
Echo A
Echo A <--This is the line it adds
Can someone please help me thanks I am very new to c++ so i guess i am doing something wrong somewere thanks.
Apr 23, 2011 at 7:07pm UTC
I tried the code and it is working fine for me.
Apr 23, 2011 at 7:25pm UTC
Umm that odd for me it justs adds the extra line at the end Echo A I am using VC++ 2008 Express
Apr 24, 2011 at 7:12am UTC
Ok thanks I managed to fix it I just needed to add this code under fgets(buffer,50,fp)
1 2 3 4
if (!feof(fp)){
//Write out each line
cout << buffer;
}
Last edited on Apr 24, 2011 at 7:13am UTC
Topic archived. No new replies allowed.