Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading