Search code examples
c++filestreamfstreamofstream

Need Help Getting New Line When Writing to File


I have the endl, but its not going into my file, so when I enter in more than 1 line, its all on the same line in the notepad.

I've tried:

codeFile << codeLine; codeFile << endl;

I've also tried adding a "\n" to the string by adding a constant string to it but it doesn't work.

//Writing Coded Lines to File:
        if(codeFile)
        {
            //Relaying Feedback to User:
            cout << "File has been successfully opened/created" << endl;
            cout << "\nWriting to file..." << endl;

            for(int i = 0; i < lines; i++)
            {
                //Getting Non-Coded Line from User:
                cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
                cin.getline(line, length);

                //Creating Copy of Line:
                strcpy(cline, line);

                //Gathering Line Length:
                length = strlen(line);

                //Coding Line:
                codedLine = code(length, line, cline, sAlphabet);

                //Coded Line Test
                cout << codedLine;

                //Writing to File:
                codeFile << codedLine << endl;
            }
        }

        //Closing File:
        codeFile.close();

        cout << "\nFile has now been closed";
    }

Solution

  • Cygwin mocks a POSIX system and uses Unix line endings, not the Windows line endings understood by NotePad.

    Replacing endl with '\n' won't help. endl is a '\n' followed by a stream flush.

    The best option is to use a different file reader, WordPad for example, that understands Unix line endings. The alternatives are to

    • Change your compiler toolchain to one that is not emulating a POSIX operating system, or
    • Brute force a Windows line ending with \r\n, but this means your code will have a similar wrong line-ending problem on a Unix -based system.