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

发布于 2024-12-05 05:41:46 字数 333 浏览 2 评论 0原文

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

示例代码:

#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;

}

I started out by declaring a string and storing all the text entered by the user in it. Then I transfer to a file. I cant figure out how add a line break to the input. I am just a beginner..

example code :

#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;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花桑 2024-12-12 05:41:46

要向输出添加换行符,您需要向其写入字符串 "\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";

To add a line break to the output, you need to write the string "\n" to it.

ofstream a_file("example.txt");

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

It's as simple as that. You can also combine the last two statements into one:

a_file << line << "\n";

But if you want to add the line break to the string, and not only to the file, you can do this:

string line = "some line that has been input";
line += "\n";
line += "the text of the second line, including the line break\n";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文