【问题标题】:How can I fix error when adding elements to my array向我的数组添加元素时如何修复错误
【发布时间】:2018-12-10 02:53:01
【问题描述】:

我正在尝试使用我已经使用过并且被证明是成功的方法将元素添加到我的文件中,但是现在当我这样做时,我得到了我想要的数字以及一堆其他不是的数字在我的文件中,没有任何意义

const int MAX_SIZE = 21;

int readSquare(int square[MAX_SIZE][MAX_SIZE], string inputFileName){ //reads file into an array

    int value;

    ifstream inFile;
    inFile.open(inputFileName);

    if (inFile) //if the input file to be read open successfully then goes on
    {
        int temp;
        inFile >> temp;

        if (temp>21) {
            temp=21;
        }
        for (int i = 0; i < MAX_SIZE; i++)
        {
            for(int j = 0; j < MAX_SIZE; j++)
            {
                inFile >> square[i][j];
            }
        }

    } else {
        inFile.close();
        return 0; //returns 0 if couldnt open file
    }
    inFile.close();

    cout << "Magic square" << endl;
    for(int i=0;i<MAX_SIZE;i++)
    {
        for(int j=0;j<MAX_SIZE;j++)
        {
            cout << square[i][j] << " ";
        }
        cout<<endl;
    }
    return 1;
}

这是我在代码中使用的文件

3
4 9 2
3 5 7
8 1 6

这是我得到的结果(持续了一段时间,但我只拿了顶部)

4 9 2 3 5 7 8 1 6 16840768 6619136 6643024 23198772 0 1942212500 127 917504 6643024 786434 6643032 0
65536 30 0 31 0 13930549 30 593 6619744 6619744 -2 127 46 6420808 1997546816 -1759127226 -2 6420704 1997359545 4096 4104
0 6420680 6634144 6619136 6421232 4104 6619744 0 3 0 4096 6420732 1997535944 6420804 655612 655360 2 9 0 2 6420976
0 1997378284 6420976 663276 1952 229640288 663200 655360 0 1997377793 6421060 661336 9 16777596 0 13080 236 661336 2 16777596 -530786634

【问题讨论】:

  • 你在用temp做什么?
  • @bvj 第一行告诉我文件中有多少行,我不希望将其添加到数组中,我将最大行设置为 21。此外,我已经尝试使用 melpomene 进行调试那些标准。我想我错过了什么
  • @Unknownzdx bvj 没有询问第一行,而是变量temp。您的代码实际上对 temp 做了什么?
  • @melpomene 它在文本中抓取文件的第一行,如果值大于 21,则将其设置为 21。除此之外它不做任何事情

标签: c++ multidimensional-array


【解决方案1】:

向@melpomene 致敬,让他们了解主要 cmets 中的细节。

Op,无论输入数据的可用性如何,您都在遍历数组的整个范围。我建议您执行以下操作,以使结果看起来不那么随机:

  • 将二维数组中的值初始化为零。
  • 将输入样本限制为您期望的数量,并且在任一维度上都不要超过数组的大小。

在您的帖子中,您在输入文件的第一行显示了3 的值。这是什么意思 - 3 行,3 个样本,或 3 行中的每一行 3 个样本?

由于输入文件每行有 3 个样本,我猜测数据文件中的初始值代表每行的样本,其中每行的值都分配给单独的 inner 数组。

不要过多偏离您的帖子,请考虑以下事项:

// clear the array for easier diags
for (int n = 0; n < MAX_SIZE; n++)
  for (int m = 0; m < MAX_SIZE; m++)
    square[n][m] = 0;

int cols;

inFile >> cols; // first line of data file indicating the samples in each row

if (cols > MAX_SIZE) // don't exceed the size of the inner array
  cols = MAX_SIZE;

for (int i = 0; i < MAX_SIZE; i++)
{
    for(int j = 0; j < cols; j++)
    {
        if (!(inFile >> square[i][j])) //  read until EOF
        {
          i = MAX_SIZE; // force outer loop to terminate since break only affects the inner loop.
          break;
        }
    }
}

见How does ifstream's eof() work?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2011-02-20
    • 2014-08-03
    • 1970-01-01
    • 2012-03-23
    相关资源
    最近更新 更多