我必须用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 ++
您不应该使用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;
}