Как вставить новую строку в текстовый файл с помощью C ++ - PullRequest
2 голосов
/ 09 октября 2019

Мне нужно написать программу на 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 ++ для этой программы.

Минимальный, воспроизводимый Пример:

#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdio.h>
#include<ctype.h>
using namespace std;
void show(char name[80])
{
    char line[800];
    cout << "Contents of the file:" << endl << endl;
    ifstream fin (name);
    while(!fin.eof())
    {
        fin.getline(line,80);
        if(fin.eof())
            break;
        cout << line;
    }
}
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;
        fflush(stdin);
        gets(line);
        fout << line << endl;
        cout << "\nDo you want to enter another line?" << endl;
        fflush(stdin);
        cin >> op;
    }
    while(tolower(op) == 'y');
    cout << "File created successfully!" << endl;
    fout.close();
    show(name);
}
int main()
{
    char name1[80];
    cout <<"Enter the name of the text file:" << endl;
    gets(name1);
    create_file(name1);
    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...