I took this function from one of my bigger programs, and made it a program in itself for the convenience of you.
anyway, it reads from a given text file, and everything works fine with it, but there is a bug:
if the file contents ends with a space, the last word is repeated. therefore, if the text file contains "hello " the output to the screen is "hello hello".
but if the text file just contains "hello" it outputs "hello" just fine..
the problem seems to lie in "filein.eof"'s ability to detect the end of the file. can anyone tell me how to fix this bug?
and i suggest compiling and running this yourself so you understand what i mean better. all you have to do is create a text file named sunday in the same folder as the project for this code (atleast if your using code::blocks), and type a sentence inside that text file. compile and run. then try it again with a space at the end. see what i mean? the last word always gets repeated if there is a space at the end of the file... please help
oh and by the way, im using windows at the moment, but if you are using linux, you must change line 10 from:
if (nday==0)*filename=((char*)"sunday.txt");
to
if (nday==0)*filename=((char*)"sunday");
since text files dont have ".txt" in linux.. anyway.. heres my code:
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 <fstream>
using namespace std;
void readnote(int nday)
{
char b[256];
char* filename[256];
cout << "Your note: \n" << endl;
if (nday==0)*filename=((char*)"sunday.txt");
ifstream filein(*filename);
for (;!filein.eof(); cout << " ")
{
filein >> b;
cout << b;
if (filein.eof()) break;
if (filein.fail()) break;
}
return;
}
int main()
{
readnote(0);
return 0;
}
| |
any help on how to fix this bug would be greatly appreciated. sorry for the lengthy description =P just trying to be specific..
and by the way, i simplified my source code
alot so you can focus on the bug.