I'm a bit puzzled as to why this is happening. If I create an ordinary string object with some text, insert it into an output stream (in the example, cout), and then insert a plain old c-string, everything is fine.
However, when I read a line into a string object from a file input stream, the resulting string object's contents are overwritten in the output stream by whatever comes after it.
I'm not sure if it's just my platform or compiler or something blatantly obvious that I'm overlooking, but any insight would greatly be appreciated.
Example:
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
// this works fine:
string str1 = "abcdefghijklmnopqrstuvwxyz";
cout << str1 << "OVERWRITE" << endl;
// result: abcdefghijklmnopqrstuvwxyzOVERWRITE
// try reading a line from a file though...
string str2;
ifstream file("test.txt");
if( file.good() ) {
getline(file, str2);
file.close();
}
cout << str2 << "OVERWRITE" << endl;
// result: OVERWRITEjklmnopqrstuvwxyz
return 0;
}
gcc version 3.4.6 on an intel i386 platform