字符串添加或减法操作员

String addition or subtraction operators

本文关键字:操作员 添加 字符串      更新时间:2023-10-16

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

    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数据类型,但我需要使用字符串。

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

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

您将一直与整数一起工作,然后在最后转换为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)中,试图猜测您的含义并添加它们,无论如何,它们都在引擎盖下进行。

这两个解决方案都有许多优势。他们的速度更快,他们报告了错误,而不是默默看上去有效,并且不需要额外的中介转换。

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