c++将int 强制转换为string
时间: 2023-03-28 20:02:39 浏览: 62
可以使用 sprintf 函数将 int 转换为字符串。例如:
int num = 123;
char str[10];
sprintf(str, "%d", num);
这样就可以将 num 转换为字符串并存储在 str 中。
相关问题
c++将string强制转换为int
在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`异常。