简体   繁体   中英

How to properly read from .txt file and assign to structs with pointer, C++

I am trying to read a file and deserialize it. I take two string in at a time and assign it to some variable foo and bar . First foo is assigned to NODE2 and ofc the bit vector, then bar is assigned to NODE2 , but when this happens foo is also assigned to NODE2 . I suspect that it has something to do with the pointers but I want to have the struct NodeReading to have a pointer to a string to relief the space of the tree that I will eventually build. I plan to have several hundred thousands of NodeReadings in a Binary tree. I just want to have the string stored as a pointer, because the strings are going to be large as well. It's only the leafs which will store an actual string (Internal nodes are used to navigate based on their bitset).

#include <iostream>
#include <fstream>
using namespace std;

struct Read {
    string dna;
    bitset<5> bf;
};

struct NodeReading {
    bitset<5> bloom_filter;
    string* dna_string;
};

static const string file = "tree.txt";
ifstream ist {file};

//could be a pair return instead of Read, but I like it this way.
Read read_line() {
    string a;
    bitset<5> b;
    ist >> a >> b;
    return Read {a, b};
}

NodeReading write_to_tree() {
    Read s = read_line();
    NodeReading hey {s.bf, &s.dna};
    return hey;
}

int main {
    NodeReading foo = write_to_tree(); //gets assigned NODE1 at first
    NodeReading bar = write_to_tree(); //gets assigned NODE2, and then foo also gets assigned NODE2

    return 0;
}

tree.txt:

NODE1 11110 NODE2 11110

Whatever happening is actually an undefined behavior. If you are doing some other processing between between these two line - NodeReading foo = write_to_tree(); & NodeReading bar = write_to_tree(); and then try to access foo , then chances that your application crashes because of segmentation fault.

Inside write_to_tree() your variable Read s is not allocated on heap, so as soon as you return from that function, variable Read s goes out of scope and you lost all the data in that. You need to allocate it on heap.

In your code struct NodeReading looks redundant. You can directly use struct Read , struct NodeReading is just a copy of struct Read 's bit field and a pointer to its string.

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