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;
        getline(cin,str);

        if(! myFile) //check file open
        {
                cout << "Error opening file" << endl;
                return -1;
        }
        myFile << str << endl;  //write file
        myFile.close(); //close file

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.