C++ >>和<<读写文本文件

执行此程序之前,必须在和该程序源文件同目录中手动创建一个 in.txt 文件,假设其内部存储的字符串为:

10 20 30 40 
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int x,sum=0;
    ifstream srcFile("in.txt", ios::in); //以文本模式打开in.txt备读
    if (!srcFile) { //打开失败
        cout << "error opening source file." << endl;
        return 0;
    }
    ofstream destFile("out.txt", ios::out); //以文本模式打开out.txt备写
    if (!destFile) {
        srcFile.close(); //程序结束前不能忘记关闭以前打开过的文件
        cout << "error opening destination file." << endl;
        return 0;
    }
    //可以像用cin那样用ifstream对象
    while (srcFile >> x) {    //读数据
        sum += x;
        //可以像 cout 那样使用 ofstream 对象
        cout<<"x="<<x<<endl;
        destFile << x << " ";   //写数据
    }
    cout << "sum:" << sum << endl;
    destFile.close();
    srcFile.close();
    return 0;
}
g++  -g main.cpp -o main
 ./main 
posted @ 2022-08-19 22:46  luoganttcc  阅读(15)  评论(0)    收藏  举报