c++字符串转化为数字
作者:野牛程序员:2024-01-03 10:23:37 C++阅读 2843
C++中可以使用std::stoi函数将字符串转换为整数,或者使用std::stof函数将字符串转换为浮点数。以下是示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int intValue = std::stoi(str); // 字符串转整数
std::cout << "整数值: " << intValue << std::endl;
std::string floatStr = "123.45";
float floatValue = std::stof(floatStr); // 字符串转浮点数
std::cout << "浮点数值: " << floatValue << std::endl;
return 0;
}请注意,如果字符串无法转换为有效的数字,这些函数将引发std::invalid_argument异常。在实际应用中,建议添加适当的错误处理机制。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++中cin的用法
- 下一篇:c++中cin读取字符串规则
