C++ int 转字符串
许久没碰c++,回来写一写发现一堆bug,都忘了怎么整了
先说最简单的方法
int i = 0;
string rel = to_string(i);
第二种
int i = 0;
string str;
stringstream stream;
stream << i;
stream >> str;
第三种
int i = 0;
char t[256];
string str2;
_itoa_s(i, t,sizeof(t), 10);//visual 2019 里用的是_itoa_s 其他我看有用itoa的,具体参见自己环境版本
str2 = t;
以下是练习的一些代码
#include <iostream>
#include<string>
#include <vector>
#include<sstream>
using namespace std;
int main()
{
string text;
char t[256];
string num;
string num2;
cout << "输入字符串" << endl;
int i = 0;
while (getline(cin,text))
{
stringstream stream;
i++;
stream << i;
stream >> num2;
_itoa_s(i, t,sizeof(t), 10);
string rel = to_string(i);
num = t;
const type_info &t1 = typeid(num);
const type_info &t2 = typeid(num2);
cout << "num1:" + num + "type:" << endl;
cout << t1.name() << endl;
cout << typeid(text).name() << endl;
cout << "num2:" + num2 + "type:" << endl;
cout << t2.name() << endl;
cout << rel
+ text << endl;
}
std::cout << "Hello World!\n";
}
如有不妥,欢迎指正