C++中如何向文件中追加文本内容

就是需要多次向某个文件输入字符串,每次输入时保留原来的内容,将要输入的内容追加到文件末尾!最好有成功的代码示例,谢谢了!!!在C++中如何加两个字符串合并到一块
???

1、首先,定义两个字符串变量str1和str2。

2、接着,输入两个字符串,保存在变量str1和str2中。

3、然后,在字符串str1后添加字符串str2,用函数append实现。

4、最后,输出字符串str1。

5、函数append中,可以使用字符串变量,也可以直接使用字符串。

6、字符串后,还可以用append函数,添加多个字符串。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-05-07

1、首先,定义两个字符串变量str1和str2。

2、接着,输入两个字符串,保存在变量str1和str2中。

3、然后,在字符串str1后添加字符串str2,用函数append实现。

4、最后,输出字符串str1。

5、函数append中,可以使用字符串变量,也可以直接使用字符串。

6、运行程序,在字符串后,添加了6个固定字符感叹号。

本回答被网友采纳
第2个回答  推荐于2017-09-28
打开文件时加上ios::app追加方式打开。即把写入的数据追加到文件尾
ofstream out;
out.open("filename",ios::app);

另外strcat()函数可以把字符串合并;
如果用string类的话就可以直接+追问

大侠可不可以说的具体一点,最好写一个示例代码,我自己写的通不过编译!?
#include
#include
#include
using namespace std;
int main()
{
ofstream ofresult( "result.txt ",iostream::append);
cout<<"这个在写文件"<<endl;
ofresult<<"123"<<"你是好孩子"<<endl;
cout<<"第二次写文件"<<endl;
ofresult<<"第二次写文件"<<endl;
return 0;}

追答

你没看我的回答 是ios::app 不是iostream::append
#include
#include
#include
using namespace std;
int main()
{
ofstream ofresult( "result.txt ",ios::app);
cout<<"这个在写文件"<<endl;
ofresult<<"123"<<"你是好孩子"<<endl;
cout<<"第二次写文件"<<endl;
ofresult<<"第二次写文件"<<endl;
return 0;}

本回答被提问者采纳
第3个回答  推荐于2017-09-16
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream ofresult( "result.txt ",ios::app);
cout<<"这个在写文件"<<endl;
ofresult<<"123"<<"你是好孩子"<<endl;
cout<<"第二次写文件"<<endl;
ofresult<<"第二次写文件"<<endl;
return 0;}
相似回答