C++中写txt文件

    xiaoxiao2021-03-25  87

    在工程中有时中间数据很多,没法每个数据全部通过cout打印出来看,这时就可以将数据全部写到一个txt文件中。这就涉及到C++中txt文件的写入操作了。下面贴出源码:

    一、头文件和类

    头文件:#inlcude<fstrteam> //文件流头文件

    类: ofstream //文件输出

    二、写入txt

    例程代码如下:

    #include<iostream> #include<fstream> #include<string> using namespace std; int main() { cout << "Start write the feature's txt" << endl; //打开要写的文件 ofstream dout("result.txt"); //例程 for(int i=0;i<10;i++) dout << i << ", "<< i+1 << ", "<< i*i << ", "<< endl; dout.close(); cout << "Finish write the feature's txt" << endl; } 注意:

    1、要写入的txt打开之后必须将其关闭才可以,不然下次写入会出问题。

    2、使用ofstream类,数据的写入可以遵循cout输出流的操作,十分简单便捷。

    生成的txt如下:

    转载请注明原文地址: https://ju.6miu.com/read-40121.html

    最新回复(0)