c++中int换成string
时间: 2024-05-26 21:06:42 浏览: 95
在C++中,可以使用标准库中的函数将int类型转换为string类型。可以使用std::to_string()
函数来实现这个转换。以下是一个示例代码:
#include <iostream>
#include <string>
int main() {
int num = 123;
std::string str = std::to_string(num);
std::cout << "转换后的字符串为:" << str << std::endl;
return 0;
}
在上面的代码中,我们首先定义了一个整数变量num
,然后使用std::to_string()
函数将其转换为字符串类型,并将结果赋值给str
变量。最后,我们使用std::cout
输出转换后的字符串。
相关问题
c++, int 转换成 string
在C++中,将整数(int 类型)转换成字符串(string 类型),可以使用标准库中的std::to_string
函数。这个函数是C++11引入的,非常方便。以下是基本的用法:
#include <iostream>
#include <string>
int main() {
int num = 42; // 一个整数示例
std::string strNum = std::to_string(num); // 将int转换为string
std::cout << "Int to String: " << strNum << std::endl;
return 0;
}
在这个例子中,num
变量被转换成了字符串strNum
。运行程序会打印出"Int to String: 42"。如果你需要在更早的C++版本中或者想避免头文件依赖,也可以手动实现字符数组或迭代器来转换。
// 如果是老版本C++
char temp[20];
itos(num, temp, 10); // 需要在头文件<cstdlib>中包含itoa
// 或者手动遍历转换
std::string manualConvert(int num) {
std::ostringstream oss;
oss << num;
return oss.str();
}
c++将int转换成string
可以使用C++标准库中的stoi函数将string类型转换为int类型。
示例代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "123";
int num = stoi(str);
cout << num << endl;
return ;
}
输出结果为:
123
相关推荐
















