简体   繁体   English

如何在C ++中将文件中的数据输入到矩阵中?

[英]How to input data from file into a matrix in C++?

I've been searching everywhere for this answer but I can't seem to find it. 我一直在到处寻找这个答案,但似乎找不到。 I was given an assignment to make a program which can add and subtract matrix. 我被分配去做一个可以加减矩阵的程序。 But the data for the matrix need to be input from a file (txt file). 但是矩阵数据需要从文件(txt文件)输入。

I'm guess that your input file, I'll call it input.txt , has a structure like: 我猜您的输入文件称为input.txt ,其结构类似于:

0 1 2 3 4
5 6 7 8 9
10 11 12 13 14

Then, I would recommend that you do: 然后,我建议您这样做:

#include <iostream>
#include <string>
#include <vector>

// ...

int main(int argc, char* argc[])
{
    // ...
    std::vector<std::vector<int> > matrix;
    std::vector<int> row;

    // ...

    char delim = ' ';

    while(std::getline(std::cin, row, delim)
    {
        matrix.push_back(row)
    }

    // ...

    return 0;
}

Then input your file like: 然后像这样输入文件:

program < input.txt

That should do the trick, but I didn't test it :) 那应该可以解决问题,但是我没有测试它:)

Happy coding! 编码愉快!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM