c++stringfilesstream

Splitting a compact string into individual ints


I am attempting to write a program that reads a file line by line, and storing the contents of each line as individual integer values. A typical line might look like this:

7190007400050083

The following snippet from my code reads a single line from the file with numbers in it:

std::ifstream file;
file.open("my_file_with_numbers");
std::string line;
file >> line;

I want the string to be split up into separate values and store them as integers in a vector. I have looked across the internet, but found no solutions. Help is much appreciated.


Solution

  • Assuming you want one value per digit, you can do e.g.

    std::vector<int> vec(line.length());
    std::transform(begin(line), end(line), begin(vec),
                   [](char const& ch)
                   {
                       return ch - '0';
                   });
    

    For the input string "7190007400050083" you will get the vector { 7, 1, 9, 0, 0, 0, 7, 4, 0, 0, 0, 5, 0, 0, 8, 3 }.


    Otherwise, how large can the numbers be? Can they be negative? Why not read it directly into integers to begin with, why use a string?

    For this, and again with an assumption that the values will all fit in a 64-bit unsigned integer type:

    std::vector<unsigned long long> vec;
    unsigned long long value;
    while (file >> value)
    {
        vec.push_back(value);
    }
    

    The above is the naive and beginner solution, but there are other ways:

    std::vector<unsigned long long> vec(
            std::istream_iterator<unsigned long long>(file),
            std::istream_iterator<unsigned long long>());
    

    For arbitrary length integer values, you need a "bignum" library like GMP.