利用C++将一个txt文档的内容读取并复制到另一个txt文档

waitingzby 2017-06-06 07:23:07
以下是我的代码:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0;
string temp;
ifstream infile;
ofstream outfile;
infile.open("C:\\Users\\waiting\\Desktop\\test.txt", ios::in);
outfile.open("C:\\Users\\waiting\\Desktop\\out.txt", ios::app);
while (!infile.eof())
{
getline(infile, temp, '\n');
outfile << temp;
}
infile.close();

}
这是是原始txt文档

这是读取后复制的另一txt文档

哪位大神知道怎么修改代码能使读取后复制到另一txt文档中的内容格式和原始txt文档里内容的格式一样,也就是说像原始txt文档里一样也是一行一行的。
另外如果我想读取原txt文档中的奇数行或是偶数行并复制到另一txt文档中又应该如何修改代码??

...全文
2585 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
森林猩 2019-11-22
  • 打赏
  • 举报
回复
把 outfile<<temp; 改成 outfile<<temp<<endl; 试试
陌上洛樱 2019-10-29
  • 打赏
  • 举报
回复 1
#include <fstream>
#include <string> 
using namespace std;

int main(){
	ifstream infile("in.txt");
	ofstream outfile("out.txt", ios::app); 
	
	char c;
	while(infile.get(c)){
		outfile <<c; 
	}
	
	infile.close();
	outfile.close();
	
	return 0;
}
题主用getline()只读取了每一行的数据, 但没读到换行符; 而用get()则读取到了文本中的每一个字符(包括换行符和空格), 所以结果复制的文本格式一致.
ipqtjmqj 2017-06-07
  • 打赏
  • 举报
回复
linux: system("cp text.txt out.txt"); windows: system("copy text.txt out.txt");
赵4老师 2017-06-07
  • 打赏
  • 举报
回复
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
    int i = 0;
    string temp;
    ifstream infile;
    ofstream outfile0;
    ofstream outfile1;

    infile.open("C:\\Users\\waiting\\Desktop\\test.txt", ios::in);
    outfile0.open("C:\\Users\\waiting\\Desktop\\out0.txt", ios::app);
    outfile1.open("C:\\Users\\waiting\\Desktop\\out1.txt", ios::app);

    while (!infile.eof()) {
        getline(infile, temp, '\n');
        i++;
        if (i%2) outfile1 << temp << endl;
        else     outfile0 << temp << endl;
    }
    infile.close();
    outfile0.close();
    outfile1.close();
    return 0;
}
gzhosp_redAnt 2017-06-07
  • 打赏
  • 举报
回复 1
在你写入txt的时候,就定义每写一行的结束就写多一个换行符。或者,你可以定义一个string,实现按行读取。 我的博客可能对你有帮助哦: http://blog.csdn.net/redrnt/article/details/70150553 http://blog.csdn.net/redrnt/article/details/72719254

15,440

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧