从 .txt 文件读取到 C++ 中的二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36708370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:37:38  来源:igfitidea点击:

Reading from .txt file into two dimensional array in c++

c++arraysfileinput

提问by Kastoli

So either I'm a complete idiot and this is staring me right in the face, but I just can't seem to find any resources I can understand on google, or here.

所以要么我是一个彻头彻尾的白痴,这正直视着我,但我似乎无法在谷歌或这里找到任何我能理解的资源。

I've got a text file which contains several lines of integers, each integer is separated by a space, I want to read these integers into an array, where each new line is the first dimension of the array, and every integer on that line is saved into the second dimension.

我有一个文本文件,其中包含多行整数,每个整数用空格分隔,我想将这些整数读入数组,其中每一行是数组的第一维,以及该行上的每个整数保存到第二维。

Probably used the worst terminology to explain that, sorry.

可能使用了最糟糕的术语来解释这一点,抱歉。

My text file looks something like this:

我的文本文件看起来像这样:

100 200 300 400 500
101 202 303 404 505
111 222 333 444 555

And I want the resulting array to be something like this:

我希望结果数组是这样的:

int myArray[3][5] = {{100, 200, 300, 400, 500},
                     {101, 202, 303, 404, 505},
                     {111, 222, 333, 444, 555}};

采纳答案by GMichael

I believe that

我相信

istream inputStream;
int myArray[3][5];
for(int i = 0; i < 3; i++)
    for(int j = 0; j < 5; j++)
        istream >> myArray[i][j];

should do what you need.

应该做你需要的。

回答by Andreas DM

In your case you can do something like this:

在您的情况下,您可以执行以下操作:

ifstream file { "file.txt" };
if (!file.is_open()) return -1;

int my_array [3][5]{};
for (int i{}; i != 3; ++i) {
    for (int j{}; j != 5; ++j) {
        file >> my_array[i][j];
    }
}

A much better way is to use std::vector:

更好的方法是使用std::vector

vector<int> my_array;
int num { 0 };
while (file >> num)
    my_array.emplace_back(num);