用c++将文件的元素加载到二维数组中

Loading elements of a file into a 2D array in c++

本文关键字:加载 二维数组 元素 c++ 文件      更新时间:2023-10-16

我对C++非常陌生(这实际上是我工作过的第一个程序),在编写这个程序时,我几乎必须学习它,但我陷入了困境。

该程序应该读取一个文本文件,将其加载到一个数组中,并为数组中的每个数字分配一个字符(因此,我想我将创建2个数组,一个包含从文件中读取的数字的int数组,以及一个包含分配给数字的字符的char数组)。然后它将打印这两个数组。然后,它应该遍历初始int数组,搜索任何值与相邻值相差一以上的数字,如果找到了这样的值,它应该给这个数字它的相邻值的平均值。它应该进行所有这些更正,然后将字符分配给这些更正后的数字,并打印出两个数组。

我真的不知道该怎么做,但我会尽量把我的问题缩小到我最初的问题。我不知道如何从文件中加载数组。我的教科书似乎很好地涵盖了数组和文件,但它并没有真正将它们结合在一起,也没有谈到从文件构建数组。

这是文件的样子,第一个数字是数组的大小。

10
7 6 9 4 5 4 3 2 1 0
6 5 5 5 6 5 4 3 2 1
6 5 6 6 7 6 8 4 3 2
1 5 6 7 7 7 6 5 4 3
5 5 6 7 6 7 7 6 5 9
5 6 7 6 5 6 6 5 4 3
5 6 7 9 5 5 6 5 4 3
5 5 6 7 6 6 7 6 5 4
5 9 5 6 7 6 5 0 3 2
5 5 5 5 6 5 4 3 2 7

这是我迄今为止的代码,尽管其中绝大多数都是关于打开文件的。我认为它至少是正确的,因为当我运行它时,我没有得到"无法打开文件错误"。

#include <iostream>
#include <fstream>
#include <array>
int main() { // Main will be in prog1_test
    //Open file
    ifstream prog1File("prog1.dat", ios::in);
    //If file can't be opened, exit
    if (!prog1File) {
        cerr << "File could not be opened" << end;
        exit(EXIT_FAILURE);
    }
        int size;
        int numArray[][];
 }

虽然我已经声明了大小和数组变量,但我不知道这是否正确,就像我说的那样,我对此还很陌生。我知道一些基本的Java,但很难弄清楚如何将其转换为c++。如有任何建议,我们将不胜感激。

只需在中将ofstream替换为ifstream,将ios:out替换为ios:out

#include <iostream>
#include <fstream>
#include <array>
int main() { // Main will be in prog1_test
    //Open file
    ifstream prog1File("prog1.dat", ios::in);
    //If file can't be opened, exit
    if (!prog1File) {
        cerr << "File could not be opened" << end;
        exit(EXIT_FAILURE);
    }
        int size;
        int numArray[][];
 }

ofstream用于写入和不读取文件,ios:out是输出打开模式,而不是输入打开模式。

我希望这能有所帮助。

我并没有真正得到洞的问题。我认为您在创建一个2D数组并从文件中读取它时遇到了麻烦。因此,这里有一些代码,从我的角度展示了如何做到这一点:

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

int main() { // Main will be in prog1_test
    //Open file
    ifstream prog1File("prog1.dat");
    //If file can't be opened, exit
    if (!prog1File) {
        cerr << "File could not be opened" << end;
        exit(EXIT_FAILURE);
    }
    int size;
    prog1File >> size;
    int[][] matrix = new int[size][];
    for (int i = 0; i < size; ++i)
    {
        matrix[i] = new int[size];
        for (int j = 0; j < size; ++j)
        {
            prog1File >> matrix[i][j];
        }
    }
    /* do your stuff */
    for (int i = 0; i < size; ++i)
    {
        delete matrix[i];
    }
    delete matrix;
    return 0;
 }