c++boost

c++ string to boost::multiprecision::cpp_int


How would I convert a string to "boost::multiprecision::cpp_int"?

Additionally, I have a .txt file with 100 numbers each of 50 digits and I use ifstream to read them line by line into a string array. How can I convert each string from the array into a cpp_int, then add all the 100 numbers and get the sum?


Solution

  • To convert a single string, use the cpp_intconstructor: cpp_int tmp("123");.

    For the text file case, read each number in a loop as a std::string via std::getline, then emplace back in a std::vector<cpp_int>. Then use the latter to compute your sum. Example:

    #include <fstream>
    #include <iostream>
    #include <string>
    #include <vector>
    
    #include <boost/multiprecision/cpp_int.hpp>
    
    using namespace boost::multiprecision;
    
    int main()
    {    
        std::vector<cpp_int> v;
        std::fstream fin("in.txt");
    
        std::string num;
        while(std::getline(fin, num))
        {
            v.emplace_back(num);
        }
        cpp_int sum = 0;
        for(auto&& elem: v)
        {
            std::cout << elem << std::endl; // just to make sure we read correctly
            sum += elem;
        }
        std::cout << "Sum: " << sum << std::endl;
    }
    

    PS: you may do it without a std::vector, via a temporary cpp_int that you construct inside the loop and assign it to sum:

    std::string num;
    cpp_int sum = 0;
    while(std::getline(fin, num))
    {
        cpp_int tmp(num);
        sum += tmp;
    }
    std::cout << "Sum: " << sum << std::endl;