Search code examples
c++c++11fstream

Separate ints from a file separated by a semicolon into different digits in C++


I need to get an input from a file. This input is any binary number of any length where the digits are separated by a semicolon like this:

0; 1; 1; 0; 1; 0;

What I would do is pass the file to a variable like

if (myfile.is_open())
{
    while ( getline (myfile,line) )
    {
        File = line;
    }
    myfile.close();
}

But I'm not sure what data type I would make the variable File be. After this I'd have to store the digits in an array or vector.


Solution

  • Basically, what you have to do, is to split your string by your delimiter (in your case, delimiter is "; "). It can be done by using std::string::find method, which returns index of character/string we look for, and std::string::substr method, which returns substring based on provided begin index (got from find) and number of characters to read (we read only 0 or 1, so length will always be 1). Once you extract desired substring, you can convert it to data type which suit your needs.

    Below is simple example how to create vector of bool's based on such string:

    #include <string>
    #include <vector>
    #include <iostream>
    
    int main()
    {
        std::string line = "0; 1; 1; 0; 1; 0; "; // In your case, 'line' will contain getline() result
        std::vector<bool> bits;
        std::size_t lastPos = 0;
    
        if(!line.empty()) bits.push_back(line.substr(0, 1) == "1");
    
        while((lastPos = line.find("; ", lastPos)) != std::string::npos)
        {
            lastPos += 2; // +2 because we don't want to read delimiter
            if(lastPos < line.size()) bits.push_back(line.substr(lastPos, 1) == "1");
        }
    
        for(auto bit : bits)
        {
            std::cout << bit << "\n";
        }
    }
    

    Output:

    0
    1
    1
    0
    1
    0