Thread: std::string object is overwritten in output stream

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    9

    std::string object is overwritten in output stream

    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

  2. #2
    Registered User
    Join Date
    May 2008
    Posts
    9
    Nevermind, figured it out. The text file was using Windows line endings and readline() uses '\n' as the delimiter, causing the string to retain the '\r', which was causing the problem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. using this as synchronization object
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 03-22-2008, 07:49 AM
  2. synchronization object choosing
    By George2 in forum C# Programming
    Replies: 0
    Last Post: 03-22-2008, 04:33 AM
  3. Replies: 4
    Last Post: 01-23-2008, 06:21 AM
  4. Really Hope I'm not Overposting (Object passing)
    By Shamino in forum Game Programming
    Replies: 10
    Last Post: 12-16-2005, 09:38 AM
  5. Help with program
    By Gamma in forum C++ Programming
    Replies: 8
    Last Post: 04-18-2002, 09:29 PM

Tags for this Thread