你将要与整数工作的全部时间,然后转换为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可能是任何C++开发人员工作中最重要的工具,除了编译器之外。你将需要它来做其他的事情,因为他们已经做了一流的工作,解决了将来会遇到的许多问题,所以最好让你开始获得经验。安装Boost所需的工作量要比使用它的时间少得多。
你是什么意思的“添加”字符串?你的意思是你有含有数字的字符串,你想添加这些数字吗?向我们展示一些示例输入和您希望看到的输出。 –
我的意思是添加像1 + 3 = 4 ... – sg552
为什么你想用字符串做数学?是否因为int太小而无法保存要计算的值?在这种情况下,您应该调查“bignum”库。 – Kevin