【问题标题】:Inputting values into a 2D array- correctly?将值输入二维数组 - 正确吗?
【发布时间】:2014-06-06 19:15:34
【问题描述】:
#include <iostream>
#include <fstream>
#include <string>       

using namespace std;

int main(){

string temp; 
ifstream in("infile.txt");
getline(in, temp);
int dim = temp.length();



char maze [dim-1][dim-1];



int i = 0;
    do{

    for(int l = 0; l<dim; ++l){

        cout<< temp.at(l);
        maze[i][l] = temp.at(l);
        cout << maze[i][l];
    }
    i++;
    cout << endl;

}while(getline(in, temp));


for(int k=0; k<dim; k++){
    for(int m=0; m<dim; m++){
        cout << maze[k][m];
    }
    cout<< endl;
}



cout<< *maze;
}

代码读取假定为正方形的文本块并将每个字符放入二维数组中。它编译并运行良好,但是当我使用最后 2 个 for 循环检查数组的值时,每行的最后一个值(即 maze[0][5]、maze[1][5]...)都是错的。似乎他们已经流血到下一行的第一个字符,但我在代码中找不到任何可以做到这一点的东西!此外,更奇怪的是,在

之前和之后立即打印的值
maze[i][l] = temp.at(l); 

是正确的!

什么改变了我的数组中的值?

【问题讨论】:

  • 为什么char maze [dim-1][dim-1];???
  • 啊,谢谢。我把索引和长度弄混了。这完全解决了问题!

标签: c++ multidimensional-array


【解决方案1】:

您必须声明大小为 dim 而不是 dim-1 的数组,因为字符串从位置 0 到 n-1 有 n 个字符,并且 n 位置处的空字符 string.length() 返回 n。

【讨论】:

    猜你喜欢
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    • 2015-10-15
    • 2017-08-01
    • 1970-01-01
    相关资源
    最近更新 更多