【问题标题】:c++ string to boost::multiprecision::cpp_intc++ string to boost::multiprecision::cpp_int
【发布时间】:2019-08-14 01:39:55
【问题描述】:

如何将字符串转换为“boost::multiprecision::cpp_int”?

此外,我有一个 .txt 文件,其中包含 100 个数字,每个数字 50 位,我使用 ifstream 将它们逐行读取到字符串数组中。如何将数组中的每个字符串转换为cpp_int,然后将所有 100 个数字相加得到总和?

【问题讨论】:

  • cpp_int i("123456789012345678901234567890");

标签: c++ boost


【解决方案1】:

要转换单个字符串,请使用cpp_intconstructor:cpp_int tmp("123");

对于文本文件情况,通过std::getline 将循环中的每个数字读取为std::string,然后放回std::vector<cpp_int>。然后使用后者来计算你的总和。示例:

#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:你可以在没有std::vector 的情况下通过一个临时的cpp_int 在循环内构造并将其分配给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;

【讨论】:

  • 感谢您的努力,但我已经找到了更好的方法(供我使用)。我只是使用: cpp_int[i] = cpp_int(mystring[i]); // 不知道是不是更好,但确实有效。
  • @sLowDowN 这正是我的意思,即创建和复制。可以将字符串分配给变量,因此您不必对值进行硬编码。
  • @sLowDowN 基本上是一样的。为了清楚起见,我明确地写了临时的,但当然你可以在循环内做sum += cpp_int{num};
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-14
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多