Sorry if this has been asked before but I have tried to find a solution elsewhere. I am using the getline function to receive input from the keyboard and save it in a text file. The problem is that it insists on printing a null character (the square box thingy) on the end of the line each time the program is run. How do I stop this? Here is my code:

string str;
        ofstream myFile("textfile.txt", ios::app);
        cout << "Enter text: " << endl;

        if(! myFile) //check file open
                cout << "Error opening file" << endl;
                return -1;
        myFile << str << endl;  //write file
        myFile.close(); //close file
10 Years
Discussion Span
Last Post by dougy83

endl puts '\n' in the file then causes the output stream to be flushed to disk. The interpretation of '\n' depends on the operating system and whether the output file was opened in text mode or binary mode.

Are you attempting write the file out on *nix operating system then transfer it to a MS-Windows where you read it with Notepad or some other text editor ? That will cause the behavior you described. Otherwise I have never had that problem.


Try stripping the last character (it will be the '\r' i.e. the ENTER key) from the your str string before writing it to your file.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.