2012-12-21 194 views
0

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

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

+0

你是什么意思的“添加”字符串?你的意思是你有含有数字的字符串,你想添加这些数字吗?向我们展示一些示例输入和您希望看到的输出。 –

+0

我的意思是添加像1 + 3 = 4 ... – sg552

+2

为什么你想用字符串做数学?是否因为int太小而无法保存要计算的值?在这种情况下,您应该调查“bignum”库。 – Kevin

回答

2

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

如果您担心正确处理非数字输入,strtol是一个更好的选择,虽然稍微罗嗦一点。 http://www.cplusplus.com/reference/cstdlib/strtol/

+2

'strtol(3)'可能比'atoi(3)'更受欢迎,因为它可以返回一个错误(通过'errno')。 –

+0

好的提示,修正答案。 – StilesCrisis

+1

@sftrabbit:不确定我同意今年向新手扔C++ 11答案是明智的。在2015年再次问我。 – StilesCrisis

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::stringint(无论采取什么方法,您都必须执行此步骤),然后添加它们,然后将其转换回std::string。在其他语言中,比如PHP,试图猜测你的意思并添加它们,无论如何,它们都是这样做的。

这两种解决方案都有很多优点。他们是faster,他们用异常报告他们的错误,而不是默默无闻地工作,他们不需要额外的中间转换。

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