如何在不使用任何图形库的情况下在c ++中创建文本编辑器?

时间:2011-09-17 12:36:16

标签: c++ file-io editor text-editor codeblocks

我首先声明一个字符串并将用户输入的所有文本存储在其中。然后我转移到一个文件。我无法弄清楚如何在输入中添加换行符。我只是一个初学者..

示例代码:

#include <iostream>
#include <fstream>

using namespace std;


int main()
{
    string x;
    string y;
    ofstream a_file("example.txt");
    getline ( cin , x);

    a_file<<x;
    a_file<<y;

}

1 个答案:

答案 0 :(得分:2)

要在输出中添加换行符,您需要将字符串"\n"写入其中。

ofstream a_file("example.txt");

string line;
if (getline(cin, line)) {
  a_file << line;
  a_file << "\n";
}

就这么简单。您还可以将最后两个语句合并为一个:

a_file << line << "\n";

但是如果你想将换行符添加到字符串中,而不仅仅是文件,你可以这样做:

string line = "some line that has been input";
line += "\n";
line += "the text of the second line, including the line break\n";