c++将string强制转换为int
时间: 2023-04-29 13:03:42 浏览: 74
在C++中可以使用std::stoi()函数将string强制转换为int。
例如:
```
std::string str = "123";
int num = std::stoi(str);
```
也可以使用std::atoi()函数
```
std::string str = "123";
const char* s = str.c_str();
int num = std::atoi(s);
```
或者使用C++11提供的std::stoll()函数将string转换为long long,std::stoull()函数将string转换为unsigned long long.
```
std::string str = "123";
long long num = std::stoll(str);
```
但是如果不是合法的数字字符串,stoi()将会抛出异常,建议在使用时进行异常处理.
相关问题
c++将string强制转换为int和double
可以使用`std::stoi()`将`std::string`转换为`int`,示例代码如下:
```c++
#include <iostream>
#include <string>
int main() {
std::string str_num = "123";
int num = std::stoi(str_num);
std::cout << num << std::endl;
return 0;
}
```
同样地,可以使用`std::stod()`将`std::string`转换为`double`,示例代码如下:
```c++
#include <iostream>
#include <string>
int main() {
std::string str_num = "3.14";
double num = std::stod(str_num);
std::cout << num << std::endl;
return 0;
}
```
需要注意的是,如果`std::string`中的内容无法转换为对应的类型,会抛出`std::invalid_argument`异常。
C++string强制转换为int
可以使用`std::stoi`函数将字符串转换为整数。例如:
```c++
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
```
输出结果为:
```
123
```