博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ 输出到文本文件
阅读量:7028 次
发布时间:2019-06-28

本文共 1772 字,大约阅读时间需要 5 分钟。

输出到文本文件

就像从文件输入数据一样,你也可以将数据输出到文件。假设你有一个矩阵,你想把结果保存到一个文本文件中。你会看到,将矩阵输出到文件的代码和将矩阵输出到终端的代码非常相似。

你需要在本地运行此代码才能看到输出的文本文件。

#include 
#include
#include
using namespace std;int main() { // create the vector that will be outputted vector < vector
> matrix (5, vector
(3, 2)); vector
row; // open a file for outputting the matrix ofstream outputfile; outputfile.open ("matrixoutput.txt"); // output the matrix to the file if (outputfile.is_open()) { for (int row = 0; row < matrix.size(); row++) { for (int column = 0; column < matrix[row].size(); column++) { if (column != matrix[row].size() - 1) { outputfile << matrix[row][column] << ", "; } else { outputfile << matrix[row][column]; } } outputfile << endl; } } outputfile.close(); return 0;}

你可以看到,你需要创建一个 ofstream 对象,然后使用该对象来创建一个新文件。

ofstream outputfile;    outputfile.open ("matrixoutput.txt");

代码的其余部分遍历该矩阵,并以你在代码中指定的格式输出矩阵:

if (outputfile.is_open()) {        for (int row = 0; row < matrix.size(); row++) {            for (int column = 0; column < matrix[row].size(); column++) {                if (column != matrix[row].size() - 1) {                    outputfile << matrix[row][column] << ", ";                }                else {                    outputfile << matrix[row][column];                }            }            outputfile << endl;         }    }

if 语句正在检查是否到达行的末尾。如果当前值是一行的结尾,则不需要在数字后加逗号分隔符:

if (column != matrix[row].size() - 1) {                    outputfile << matrix[row][column] << ", ";                }                else {                    outputfile << matrix[row][column];                }

 

转载于:https://www.cnblogs.com/fuhang/p/9056803.html

你可能感兴趣的文章
双链表的基本操作
查看>>
走进异步编程的世界 - 剖析异步方法(上)
查看>>
[HAOI2006]受欢迎的牛
查看>>
docker-maven-plugin 完全免Dockerfile 文件
查看>>
day20 Python 装饰器
查看>>
限制性与非限制性定语从句区别
查看>>
fiddler工具的使用
查看>>
jquery源码分析(二)——架构设计
查看>>
javascript深入理解js闭包(转)
查看>>
207. Course Schedule
查看>>
如何优化您的 Android 应用 (Go 版)
查看>>
Trie树实现
查看>>
Opencv无法调用cvCaptureFromCAM无法打开电脑自带摄像头
查看>>
Exception异常处理机制
查看>>
复杂的web---web中B/S网络架构
查看>>
编写文档的时候各种问题
查看>>
Eclipse里maven的project报Unbound classpath variable: 'M2_REPO/**/***/***.jar
查看>>
新旅程CSS 基础篇分享一
查看>>
查看内核函数调用的调试方法【原创】
查看>>
个人项目中遇到的问题
查看>>