[英]How to append text to a text file in C++ without delete the data in file
如何在 C++ 中将文本附加到文本文件而不删除文件数据中的文件 ex 中的数据,例如 hello,当我打开此文件并写入 world 时,该文件将类似于 hello world
我假设您习惯于使用“fstream”读取/写入文件
如果“input.txt”有以下内容
Hello
如果你运行下面的简单代码,
#include <fstream>
int main()
{
std::ofstream ofs;
ofs.open("input.txt", std::ios::out|std::ios::app);
ofs << "\nWorld";
ofs.close();
return 0;
}
您可以在下面看到结果文本文件
Hello
World
ios::out
设置为写入模式
ios::app
在文件末尾追加数据。
我稍微修改了你的代码。 如果在键入姓名时键入“exit”,则该过程将停止。
#include<string>
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
std::string data;
std::string data2;
std::string data3;
std::ofstream ofs;
ofs.open("input.txt", std::ios::out|std::ios::app);
cout<<"plz enter ur name ";
cout<<"plz enter ur age ";
cout<<"plz enter ur country";
while (std::getline(std::cin, data) && data!="exit")
{
std::getline(std::cin, data2);
std::getline(std::cin, data3);
ofs << data << "\t" << data2 << "\t" << data3 << endl;
}
ofs.close();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.