C++ 輸出到文本文件


輸出到文本文件

就像從文件輸入數據一樣,你也可以將數據輸出到文件。假設你有一個矩陣,你想把結果保存到一個文本文件中。你會看到,將矩陣輸出到文件的代碼和將矩陣輸出到終端的代碼非常相似。

你需要在本地運行此代碼才能看到輸出的文本文件。

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main() {

    // create the vector that will be outputted
    vector < vector <int> > matrix (5, vector <int> (3, 2));
    vector<int> 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];
                }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM