简体   繁体   中英

C++ trying to read data from file into vector

I'm simply trying to read data from file into a vector. The file, as showed in the image, I'm trying to read from contains the first number (n) which is the number of nodes. After that, I read n numbers of weight. Finally, I get the the connection from the adjacency matrix. When I compile my code it stops working.

int main()
{
    ifstream inFile;
    string tline;

    inFile.open("Problem.dat_50_50_0");

    if(!inFile)
        cout << "OPSS" << endl;

    inFile >> tline;
    inFile >> n;

    for(int i = 0; i < 2 * (n + 1); i++)
        inFile >> tline;

    vector<vector<int> > matrix(n, vector<int>(n));
    vector<list<int> > adj(n);
    vector<int> weight(n);
    vector<int> degree(n);
    vector<string> color(n, white);

    for(int i = 0; i < n; i++)
    {
        inFile >> weight[i];
        weight.push_back(weight[i]);
    }

    inFile >> tline;

    for(int i = 0; i < n; i++)
        for(int j = 0; j < n; j++)
        {
            inFile >> matrix[i][j];

            if(i == j)
                matrix[i][j] = 0;
            if(matrix[i][j] == 1)
                adj[i].push_back(j);
        }
}

I'm trying to open the file to read the first line, put this number into n , and then push_back into a vector the n th number after the first line (which represents the weight as shown in the picture). After reading the weight, we go to the matrix to get the neighbors. If matrix[i][j] == 1 , we put the value of j into the adjacency vector.

For example, according to the pictures, the adj vector will be like so:

0 -> 1, 2
1 -> 0, 2, 3
2 -> 0, 1
3 -> 1

Why dont you write data like this?: 4;12,2365,85;6,11,12,8; Much easier to split and parse..

Or use name=value list..

Hope this helps.. Just how i know it best.

This block looks wrong:

for(int i =0; i < n ; i++){
    inFile>> weight[i];
    weight.push_back(weight[i]);
}

You are taking the number from inFile and putting it into weight[i] , then, on the following line, you push_back the same value again, but then you will overwrite it at the next iteration (because i has increased in the meanwhile). This means that if your numbers coming from the file are 1 2 3 4 you will end up with these results at the end of each iteration: 1 1 , 1 2 2 , 1 2 3 3 , 1 2 3 4 4 . inFile>> weight[i]; alone is enough.

Then, I don't think this is the problem that is blocking you, but...

if(! inFile){
    cout << "OPSS" << endl;
}

If you can't read the file, you should not only print "OPSS", you should exit, or throw an exception. Anyway, you can't just continue, because the rest of the code expects the file to be there.

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