【问题标题】:String addition or subtraction operators字符串加法或减法运算符
【发布时间】:2012-12-09 10:31:27
【问题描述】:

如何加减字符串的值?例如:

    std::string number_string;
    std::string total;

    cout << "Enter value to add";
    std::getline(std::cin, number_string;
    total = number_string + number_string;
    cout << total;

这只是附加字符串,所以这不起作用。我知道我可以使用 int 数据类型,但我需要使用字符串。

【问题讨论】:

  • “添加”字符串是什么意思?你的意思是你有包含数字的字符串并且你想添加这些数字吗?向我们展示一些示例输入和您希望看到的输出。
  • 我的意思是添加像 1+3=4 ...
  • 为什么要用字符串来做数学?是因为 int 太小而无法容纳您要计算的值吗?在这种情况下,您应该调查“bignum”库。
  • C++ 没有任何内置函数可以满足您的要求。你需要自己写。
  • 您是要添加小数字(小于 10 位左右)还是非常大的数字(约 10 位以上)?

标签: c++ string operators


【解决方案1】:

您需要一直使用整数,然后在最后转换为 std::string

如果你有一个支持 C++11 的编译器,下面是一个可行的解决方案:

#include <string>

std::string sum(std::string const & old_total, std::string const & input) {
    int const total = std::stoi(old_total);
    int const addend = std::stoi(input);
    return std::to_string(total + addend);
}

否则,使用boost:

#include <string>
#include <boost/lexical_cast.hpp>

std::string sum(std::string const & old_total, std::string const & input) {
    int const total = boost::lexical_cast<int>(old_total);
    int const addend = boost::lexical_cast<int>(input);
    return boost::lexical_cast<std::string>(total + addend);
}

该函数首先将每个std::string 转换为int(无论采用何种方法,您都必须执行此步骤),然后添加它们,然后将其转换回std::string。在其他语言中,例如 PHP,尝试猜测您的意思并添加它们,无论如何,它们都是在后台执行此操作。

这两种解决方案都有许多优点。他们是faster,他们通过异常报告他们的错误,而不是默默地表现出来,并且他们不需要额外的中间转换。

Boost 解决方案确实需要进行一些设置工作,但绝对值得。 Boost 可能是任何 C++ 开发人员工作中最重要的工具,除了编译器。您将需要它来做其他事情,因为他们已经完成了一流的工作,解决了您将来会遇到的许多问题,因此您最好开始获得它的经验。安装 Boost 所需的工作比使用它节省的时间要少得多。

【讨论】:

    【解决方案2】:

    您可以使用atoi(number_string.c_str()) 将字符串转换为整数。

    如果您担心如何正确处理非数字输入,strtol 是一个更好的选择,尽管有点冗长。 http://www.cplusplus.com/reference/cstdlib/strtol/

    【讨论】:

    • strtol(3) 可能比atoi(3) 更受欢迎,因为它可以返回错误(通过errno)。
    • 好提示,修正答案。
    • @sftrabbit:不确定我是否同意今年向新手抛出 C++11 答案是否明智。 2015 年再问我一次。
    • 首先我想投反对票,因为真的没有理由使用 ac 构造(两者都以其独特的方式存在缺陷),但后来我想起了 c++ 解决方案本身是多么可怕,所以继续+1
    • @David 必须包含 boost 来解析整数对于初学者来说并不是一个很好的解决方案。所以在 c++11 之前的 C++ 方式将是 std::string s = "100"; int i; std::istringstream ss(s); ss &gt;&gt; i; char c; if (ss.fail() || ss.get(c)) // not a number - 这一定是任何高级语言中最可怕的 int 解析代码。让我们希望 c++11 变得更加普及,我们可以忘记这些东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多