Home > OS >  Best way to read a files contents and separate different data types into separate vectors in C
Best way to read a files contents and separate different data types into separate vectors in C

Time:12-12

I'm fairly new to the C syntax and wondered if someone could provide how they would approach a problem I have.

My task is to read a files txt contents which contains a combination of strings and integers. I then need to store all the integers into one vector and all strings into another vector. I have managed to store all the contents into a vector, but now I want to separate the different data types into their own vectors, however I'm struggling to find the best approach for this. Would I iterate through the whole vector and then use if conditions for the data types, or is there another way? I have posted an example of my read file code and file to give you a clearer understanding of what I mean.

Thanks,

// Basic read file code

    fstream file("filepath.txt", ios::in); // reads file
    string line;  // temp storage of lines in file
    vector<string> lines; // creates for permanent storage  
    while (getline(file, line))
    {
        lines.push_back(line);
    };  // pushes each line to back of vector until file end.

file example - each string is a question with the line below being the answer as an int. 88 lines in total.

1, string"
2, int
3,"string"
4, int
5,"string"
6, int

CodePudding user response:

You should create two vectors and push_back data alternately, hope this help :)

CodePudding user response:

You got almost there, the code in your example is good. Just missing a second step:

    // storage
    std::vector<int> integers;
    std::vector<std::string> strings;

    // open file and iterate
    std::ifstream file( "filepath.txt" );
    while ( file ) {

        // read one line
        std::string line;
        std::getline(file, line, '\n');

        // create stream for fields
        std::istringstream ils( line );
        std::string token;

        // read integer (I like to parse it and convert separated)
        if ( !std::getline(ils, token, ',') ) continue;
        int ivalue;
        try { 
            ivalue = std::stoi( token );
        } catch (...) {
            continue;
        }
        integers.push_back(  ivalue );

        // Read string
        if ( !std::getline( ils, token, ',' )) continue;
        strings.push_back( token );
    }

Godbolt: https://godbolt.org/z/4aMv6MW4K

BTW the using std; practice can bite you in the future. Try to keep the std:: prefix in the code, it's safer.

  • Related