C++将string转换为integer
时间: 2024-02-11 14:21:59 浏览: 28
要将 C++ 中的字符串转换为整数,可以使用 `std::stoi` 函数。以下是一个示例代码:
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
```
在上面的示例中,`std::stoi` 函数将字符串 `"12345"` 转换为整数,并将结果存储在变量 `num` 中。然后,我们通过 `std::cout` 输出该整数。你可以根据实际需要修改字符串的值和输出方式。
相关问题
将string转换为int
可以使用语言内置函数或者库来将string转换为int。以下是几个常见的示例:
在C++中,可以使用stoi函数来实现:
```
#include <string>
#include <iostream>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << num << std::endl; // 输出 123
return 0;
}
```
在Python中,可以使用int函数来实现:
```
num = int("123")
print(num) # 输出 123
```
在Java中,可以使用Integer.parseInt函数来实现:
```
String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // 输出 123
```
c++将int转为string
在 C++ 中将一个整数转换为字符串可以使用 `to_string()` 函数。下面是一个示例:
```c++
#include <iostream>
#include <string>
int main() {
int num = 42;
std::string str_num = std::to_string(num);
std::cout << "The integer " << num << " converted to string is: " << str_num << std::endl;
return 0;
}
```
输出:
```
The integer 42 converted to string is: 42
```