字符串添加或减法操作员
String addition or subtraction operators
如何添加或减去字符串的值?例如:
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所需的工作要比您通过使用它节省的时间要少得多。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 使用enable_if添加过载操作员==
- C 继承添加操作员
- STD :: MAP-使用下标操作员与插入方法添加元素
- 超载添加操作员和动态向量的分割故障
- 简单的方法将隐式类型促销添加到std ::复杂类操作员
- 读取文件时添加操作员
- 字符串添加或减法操作员
- 在C 中添加两个对象(操作员过载)
- 在表达树中添加一元操作员