C++实现简单的从文本读写数据
以下代码可直接运行:
#include<fstream>
#include<iostream>//ifstream和ofstream从该头文件取得
using namespace std;
int main() {
ofstream fout;
ifstream fin;//这两个变量的定义由头文件<fstream>包含
fin.open("输入.txt");
fout.open("输出.txt", ofstream::app);
int ch1, ch2;
while(1){
if (fin.eof())//我在输入文件中保证了每次读取两个数字文件恰好结束,不确定的的建议行判定一次输入一次
break;
fin >> ch1 >> ch2;
fout << ch1 + ch2 << endl;
}
fin.close();
fout.close();
return 0;
}
输入.txt样例:
1 1
2 2
3 3
4 4
输出.txt样例
2
3
4
5
6
8