1

I wanna load a multidimentional array from a file, I have this code:

std::vector<std::vector<int>> matrix;
for (int r = 0; r < cols; r++)
{
    std::vector<int> row;
    for ( int c = 0 ; c < cols ; c++ )
    {
        int temp;
        if ( fin >> temp )
        {
            std::cout << temp;
            row.push_back(temp);
        }
    }
    matrix.push_back(row);
}

Cols variable is fine, the nested loop is called 9 times if I have 3x3 array, so this works as expected...However it seems that the file cannot read single integer (fin >> temp). Fin is the file handler. What's wrong?

File content:

0 1 1
0 0 1
1 1 1

The whole code:

std::vector<std::vector<int>> foo()
{
    std::string filename;
    std::cout << "Filename: ";
    std::cin >> filename;

    std::vector<std::vector<int> > matrix;
    std::ifstream fin(filename);
    if(!fin) {
        std::cout << "Error";
        exit(EXIT_FAILURE);
    }

    std::string line;
    int cols = 0;
    if(fin.is_open()){
        while(!fin.eof()){
            std::getline(fin,line);
            cols++;
        }
    }
    for (int r = 0; r < cols; r++)
    {
        std::vector<int> row;
        for ( int c = 0 ; c < cols ; c++ )
        {
            int temp;
            if ( fin >> temp )
            {
                std::cout << temp; // displays nothing
                row.push_back(temp);
            }
                        std::cout << temp; // displays some crap like -84343141
        }
        matrix.push_back(row);
    }
    std::cin >> filename; // to stop execution and see the results
    return matrix;
}
4

3 回答 3

2

You are doing a first pass through the file to determine the size, but you are going to need to reopen the file after reading it the first time. Otherwise, there is no data left in the file to read.

于 2013-06-15T11:34:07.717 回答
0

Try to add

fin.seekg (0, is.beg);

before the for cycle.

Because in

std::string line;
int cols = 0;
if(fin.is_open()){
    while(!fin.eof()){
        std::getline(fin,line);
        cols++;
    }
}

you will get the position in file at the eof and

if ( fin >> temp )

will always return false. That is why you need to set the position to the beginning of the file.

You can also replace

while(!fin.eof()){
        std::getline(fin,line);
        cols++;
    }

with easier

while(std::getline(fin,line)) cols++;
于 2013-06-15T11:39:33.910 回答
0

First read the file, and calculate the number of rows and columns, then close the file. Then again read the file, and now loop up to the calculated rows and columns

于 2013-06-15T12:45:42.600 回答