【问题标题】:File input into a dynamic 2D array文件输入到动态二维数组
【发布时间】:2014-03-17 19:18:18
【问题描述】:

我正在尝试创建一个程序来为游戏挂钩纸牌生成解决方案。但是我真的被困在开始部分。它正在获取一个包含起始板的文件,而不是将这些值放在动态二维数组中。目前,当我运行我的程序时,我得到错误消息下标超出范围。因此,起始板从 txt 文件的第一行开始,其中包含两个代表行和列的数字,然后是板本身包含字符。我的解构器和 tostring 被注释掉了,因为它们也有问题,我认为它们是连接的。

例如(不是一个实际的板,只是表示我希望加载到二维数组中的 NxN 和 char)

3 3

sss

sss

sss

头文件

#pragma once
#include <string>
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
typedef unsigned char PegType;

class PegBoard
{
private:
   int numRows;
   int numCols;
   char ** pegBoard;

public:
//constructor
PegBoard(istream &input);

//deconstructor
 ~PegBoard();


//toString
 void toString() ;
}; //end of header file

实现文件

  #include "PegBoard.h"

//constructor
PegBoard::PegBoard(istream &input){
 string dummyline;
 numCols = 0;
 numRows = 0;
 pegBoard = new char* [numRows];

 //get rows and cols
 input >> numRows;
 input >> numCols;
 //generate starting board from txt file
    while(!input.eof()){
        for(int r=0; r <= numRows; r++){  
            getline(input,dummyline);
            pegBoard[r] = new char[numCols];
            for(int c=0; c<= numCols; c++){
                 pegBoard[r][c] = dummyline[c];
            }
        }
    }
}//end constructor

//deconstructor
PegBoard::~PegBoard(){
//  for (int i=0; i <= numRows; i++)
    //  delete [] peg[i];
    //  delete [] peg;
}//end deconstructor

//toString
void PegBoard::toString() {
    /*
    for(int r=0; r<numRows; r++){
        for(int c=0; c<numCols; c++)
            cout << peg[r][c];
            cout << endl;
    }
    */
}

【问题讨论】:

    标签: c++ dynamic multidimensional-array


    【解决方案1】:

    你在做什么不好,非常糟糕的是你在从文件中分配值之前使用 numRows。 所以改成这样:

     //get rows and cols
     input >> numRows;
     input >> numCols;
    pegBoard = new char* [numRows];
    

    在你的 for 循环中,你只应该从 0 到 numRows (numCols) -1。或者像这样:

    for(int r=0; r < numRows; r++)
    

    因为当你定义数组大小时,你说的是numRows,所以我们计算[0,numRows)

    【讨论】:

    • 我觉得自己很傻,但我做了这个更改,但仍然收到相同的错误消息。
    猜你喜欢
    • 2011-01-14
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多