如何在行和列中显示矩阵文件

How to display matrix file in rows and columns

本文关键字:显示 文件      更新时间:2023-10-16

请原谅我的代码格式,因为我刚开始使用C++。无论如何,我正在尝试读取和显示文本文件中的内容(以矩阵的形式)。

虽然我可以在文件中读取,而不是像在文本文件中那样显示输出,而是在一行中获取所有内容。我不能强行执行代码,因为我有几个文件的矩阵不同。

例如。matrix01

9 7 6
8 -1 0

或matrix02

2 10
3 5
-7 25

下面的代码是我的文件输入,那么我该怎么做才能把它变成行和列,而不是单行/行呢?

#include <iostream>
#include <fstream>
using namespace std;
int main(){
    ifstream fin;  //file input stream
    ofstream fout; //file output stream
    fin.open("/Desktop/matrix_a.txt");
    fout.open("/Desktop/matrix_a.out");
    string msg;

    while (fin>>msg){//read until eof
      cout << msg << " ";
    }

    fin.close();
    fout.close();
}

您的状态:

我把所有内容都放在一行里。

您的代码执行以下操作:

 while (fin>>msg){//read until eof
   cout << "" << msg << " ";
 }

这是因为在这里,您没有将std::endl写入std::cout,并且在任何时候都不会打印新行。operator<<不会自动在语句末尾添加换行符。如果你愿意,你有责任这么做。