首页 > 代码库 > C++ int与string或者char*之间的转换总结

C++ int与string或者char*之间的转换总结

#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main(void)
{
	//method1
	char buf[4];
	itoa(123,buf,10);		//自动添'\0'
	cout<<buf<<endl;
	char buf1[]="567";
	int var=atoi(buf1);
	cout<<var<<endl;

	//method2
	int var1=345;
	stringstream ss;
	ss<<var1;
	string str;
	ss>>str;
	cout<<str.c_str()<<endl;
	ss.clear();		//这里注意清空
	str="678";
	ss<<str;
	ss>>var1;
	cout<<var1<<endl;

	//单向转
	int var2=200;
	char buf2[4];
	sprintf(buf2,"%d",var2);
	cout<<buf2<<endl;

	system("pause");
	return 0;
}