如何使用C ++在文本文件中插入新行

问题描述 投票:0回答:1

我必须用C ++编写一个程序,要求用户输入行并将其存储在文本文件中。

void create_file(char name[80])
{
char line[80],op;
ofstream fout(name);
do
{
    cout << "Enter the line you want to enter in the file:" << endl << endl;
    gets(line);
    fout << line << endl;
    cout << "\nDo you want to enter another line?" << endl;
    cin >> op;
}
while(tolower(op) == 'y');
cout << "File created successfully!" << endl;
fout.close();
}

问题是文本没有存储在不同的行中。

我必须为此程序使用TURBO C ++

c++ turbo-c++
1个回答
0
投票

您不应该使用gets。我将其替换为std::geline。同时使用std::string会更容易。我添加了std::cin.ignore()。否则,换行符将留在流中并由std::geline读取。

#include <fstream>
#include <iostream>

void create_file(std::string name) {
    std::string line;
    char op;
    std::ofstream fout(name);
    do {
        std::cout << "Enter the line you want to enter in the file:\n\n";
        std::getline(std::cin, line);
        fout << line << '\n';
        std::cout << "\nDo you want to enter another line?\n";
        std::cin >> op;
        std::cin.ignore();
    } while(std::tolower(op) == 'y');
    std::cout << "File created successfully!\n";
    fout.close();
}

int main() {
    create_file("Text.txt");
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.