G
gukn9700
When I used fstream to handle a file, I met with a very weird thing:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream outfile;
outfile.open("test.txt", ios_base::in | ios_base:ut);
if (!outfile)
{
cout << "open file fail!\n";
return -1;
}
//display original text
char ch;
while (outfile.get(ch))
{
cout << ch;
}
cout << '\n';
outfile.clear(); //clear eofbit
//seek to end of the text
outfile.seekp(0, ios_base::end);
//get input from the user and append it to outfile
while (cin.get(ch))
{
outfile.put(ch);
}
outfile.close();
return 0;
}
the content of test.txt is:
This is a text
only for test.
But after I ran the program, it turned out to be:
ThThis is a text
only for test.
abcdefg
The "abcdefg" was the input. But, where did the additional "Th" come
from?
What's wrong with my program?
Compiler: gcc3.2.3
System: Windows2000
Compile option: -ansi -Wall
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
fstream outfile;
outfile.open("test.txt", ios_base::in | ios_base:ut);
if (!outfile)
{
cout << "open file fail!\n";
return -1;
}
//display original text
char ch;
while (outfile.get(ch))
{
cout << ch;
}
cout << '\n';
outfile.clear(); //clear eofbit
//seek to end of the text
outfile.seekp(0, ios_base::end);
//get input from the user and append it to outfile
while (cin.get(ch))
{
outfile.put(ch);
}
outfile.close();
return 0;
}
the content of test.txt is:
This is a text
only for test.
But after I ran the program, it turned out to be:
ThThis is a text
only for test.
abcdefg
The "abcdefg" was the input. But, where did the additional "Th" come
from?
What's wrong with my program?
Compiler: gcc3.2.3
System: Windows2000
Compile option: -ansi -Wall