在编程时,我们经常会遇到需要将不同类型的数据进行相互转换的情况。例如,在C++中,`string`类型和`int`类型的相互转换就是常见的需求之一。今天,我们就来聊聊如何在C++中实现这种转换。
📚 string转int:
将字符串转换为整数可以使用标准库中的`std::stoi()`函数。这个函数非常方便,只需要传入一个字符串参数,它就能返回对应的整数值。例如:
```cpp
include
include
using namespace std;
int main() {
string str = "123";
int num = stoi(str);
cout << num; // 输出 123
return 0;
}
```
💡 int转string:
反过来,将整数转换为字符串则可以通过`std::to_string()`函数来实现。这个函数接受一个整数作为输入,并返回对应的字符串形式。例如:
```cpp
include
include
using namespace std;
int main() {
int num = 456;
string str = to_string(num);
cout << str; // 输出 "456"
return 0;
}
```
这两种方法都能很好地帮助我们在C++中实现`string`和`int`之间的转换,让我们的代码更加灵活和高效。希望这些小技巧能帮到你!🚀