简体   繁体   中英

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. 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.

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 .

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? I have questions about that as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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