写入文件时需要帮助获得换行

时间:2019-03-24 17:06:08

标签: c++ filestream fstream ofstream

我有endl,但是它没有进入我的文件,因此当我输入多于1行时,其全部位于记事本中的同一行。

我尝试过:

codeFile << codeLine; codeFile << endl;

我还尝试通过向字符串中添加常量字符串来添加“ \ n”,但这是行不通的。

//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";
    }

1 个答案:

答案 0 :(得分:1)

Cygwin模拟POSIX系统并使用Unix行尾,而不是NotePad理解的Windows行尾。

endl替换为'\n'将无济于事。 endl'\n',后跟流刷新。

最好的选择是使用其他文件读取器,例如WordPad,它可以理解Unix行尾。替代方法是

  • 将您的编译器工具链更改为不模拟POSIX操作系统的工具链,或者
  • Brute强制Windows行以\r\n结尾,但这意味着您的代码在基于Unix的系统上也会有类似的错误行尾问题。
相关问题