简体   繁体   English

从文件中逐行读取并存储到二维数组中

[英]Reading line by line from a file and storing into a 2d array

I'm trying to read line by line from a file and storing it into a 2-d array.我正在尝试从文件中逐行读取并将其存储到二维数组中。 I'm getting a very odd out put which is the screenshot below.我得到了一个非常奇怪的输出,这是下面的屏幕截图。 The input file looks like:输入文件如下所示:

-x-
xx-
--x

and the code looks like:代码如下:

int counter=-1;
while(getline(InputFile,line))
{
    counter++;
    //cout<<"line size is "<<line.size()<<endl;

    for (int i=0;i<NumOfColms;++i)
    {
        if (line[i]=='-')
        {
            //cout<<"0 ";
            CurrentArray[counter][i]=0;
        }
        else if (line [i]=='X'||line [i]=='x')
        {
            //cout<<"x ";
            CurrentArray[counter][i]=1;
        }
    }
    //cout<<endl;

    for (int i=0;i<NumOfRows;++i)
    {
        for (int j=0;j<NumOfColms;++j)
        {
            cout<<CurrentArray[i][j]<<" ";
        }
        cout<<endl;
    }
}

SCREENSHOT截屏

The reason you have such odd output is because you are printing out the content of your CurrentArray in full after every line you read.您有如此奇怪的输出的原因是因为您在阅读的每一行之后都完整地打印出CurrentArray的内容。 So from your image this looks like this:所以从你的图像来看,这看起来像这样:

Line -x- read
0 1 0 //-- CurrentArray[0][0..1..2], which is -x-
7431232 7407000 1951160272 //-- CurrentArray[1][0..1..2]
7406760 7407000 0 //-- CurrentArray[2][0..1..2]

Line xx- read
0 1 0 //-- CurrentArray[0][0..1..2], which is -x-
1 1 0 //-- CurrentArray[1][0..1..2], which is xx-
7406760 7407000 0 //-- CurrentArray[2][0..1..2]

Line --x read
0 1 0 //-- CurrentArray[0][0..1..2], which is -x-
1 1 0 //-- CurrentArray[1][0..1..2], which is xx-
0 0 1 //-- CurrentArray[2][0..1..2], which is --x

As you can see, 1st and 2nd iteration prints out some garbage, which was in memory when you allocated space for CurrentArray , but only 3rd prints correct data because by then you have all elements assigned proper values.如您所见,第 1 次和第 2 次迭代打印出一些垃圾,这些垃圾在您为CurrentArray分配空间时在内存中,但只有第 3 次打印出正确的数据,因为到那时您已为所有元素分配了正确的值。

Solution: Move your printing out loop out of while scope and place it after it, so when the while loop is done, you have assigned values to all elements of CurrentArray .解决方案:将打印输出循环移出while范围并将其放在它之后,因此当while循环完成时,您已将值分配给CurrentArray所有元素。

I am guessing here, but without seeing the code in which you declare, allocate memory for, and null terminate your arrays, I would assume that that would need to be fixed.我在这里猜测,但没有看到您声明、分配内存和空终止数组的代码,我认为这需要修复。 The output that you got suggests that you are probably overrunning your array for some reason, because you are getting what looks to be garbage data as output.您得到的输出表明您可能出于某种原因超出了数组,因为您得到的输出看起来是垃圾数据。 I have seen this happen before.我以前见过这种情况。

Also, how are NumOfRows and NumOfColumns calculated?另外, NumOfRowsNumOfColumns是如何计算的? I have questions about that as well.我对此也有疑问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM