C++:将输出结果写入文件、从文件中读取数据

应用背景

很多时候我们会使用语句:

cout << ... << endl ;

来进行将某个变量的值展示在屏幕上,但如果我们希望将这个结果写入文件中

该怎样操作呢?

下面展示了如何将输出结果写入txt文件之中 

#include <iostream>

using namespace std ; 

int main()
{
    int x, y ; 
    cin >> x >> y ; 
    freopen("test.txt","w",stdout) ; // 将标准输出重定向到text.txt文件

    if (y == 0) cerr << "error." << endl ; // 除数为0则输出错误信息
    else cout << x / y ; // 否则将结果写入test.txt

    return 0 ;
}

相似的,如果我们希望从文件中读取数据用于 cin >> 输入 

可以参考下面例子 

#include <iostream>

using namespace std ; 

int main()
{
    int n ; 
    freopen("test.txt","r",stdin) ; //从test.txt中读取数据
    cin >> n ; 
    cout << n << endl ; 
    return 0 ;
}

猜你喜欢

转载自blog.csdn.net/m0_54689021/article/details/128521318