简体   繁体   中英

Reading in data from .txt file into structs

I have a file and I want to read in those elements into structs.

The file is structured like this:

n
m
lat1 lon_1
...
lat_n lon_n
nodeStart_1 nodeTo_1 nodeweight_1
...
nodeStart_m nodeTo_m nodeweight_m\

And this is the content of my file:\

3
4
48.5 6.6
48.3 5.5
48.3 4.8
23 24 25
26 27 28
29 30 31
29 41 43\

The numbers inside the file are just random ones.

n and m are integers, lan and lon are floats and the m edges are integers as well.
I have n nodes and m edges. So the 2nd to the n+2nd line should be read into nodeGr and all the m lines after that should be read into edgeGr. These are my structs:

struct edgeGr{
    int s,t,c;
}

struct nodeGr{
    float lat, lon;
};

And here is my code, which doesn't work properly: The problem is with reading in the nodes. I got it to work with lat and lon being integers but not with them being floats. When lat and lon are floats my edges are behaving weird and just become 000. I am not sure what exactly is wrong anymore since I tried way too many things and none of them work. Can you help me or give me some hints?

EDIT: it now works but the while loop is being executed twice, why is that?

void readGraph(std::ifstream & in, struct edgeGr edges[], struct nodeGr nodes[]){
    int n;
    int m;

    while (!in.fail()){
        in >> n;
        in >> m;

        for (int i = 0; i < n; i++) {

            //TODO: get this to work
            in >> nodes[i].lat >> nodes[i].lon;

        }
        for (int i = 0; i < m; i++) {
            in >> edges[i].s >> edges[i].t >> edges[i].c;
            std::cout << edges[i].s << edges[i].t << edges[i].c << '\n';
            //This prints out all my edges just fine but twice and only if lat and lon are integers.
        }
    }
    in.close();
    std::cout << m << " " << n;

};

int main() {
    std::ifstream in("test.txt");


    nodeGr nodes[3]; //3 should be n
    edgeGr edges[4]; //4 should be m

    readGraph(in, edges, nodes);
    std::cout << '\n' << edges[1].s <<" "<< edges[1].t <<" "<< edges[1].c << '\n';
    return 0;
}

it now works but the while loop is being executed twice, why is that?

 while (.in.fail()){

Because the read doesn't fail in the first iteration.

If you want to have the content of the loop be executed once, you can easily achieve that by moving it outside the loop.


Note that hard-coding the size of the array, and the accepting user input to access indices of the array without validation is a recipe for buffer overflow.

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