好久没有写C++程序了,感觉陌生了好多,单是一个int和string的互相转换就搞了老半天,为了方便以后的工作,将它们写下来以供参考。
1.int转成string
a、使用stringstream对象:
1: #include <iostream>2: #include <string>3: #include <sstream>4: using namespace std;5: int main(){6: stringstream ss;7: int result=1000;8: string str;9: ss<<result;10: ss>>str;11: cout<<str<<endl;12: return 0;13: }b、使用sprintf函数,函数原型:int sprintf( char *buffer, const char *format [, argument] ... ),转换后的字符串存储在buffer中,format的使用类似于printf函数,后边的可选参数就是需要转换的参数,示例如下:1: #include <iostream>2: #include <string>3: #include <sstream>4: using namespace std;5: int main(){6: int result=1000;7: char buffer[100];8: sprintf(buffer,"%d",result);9: string str(buffer);10: cout<<str<<endl;11: return 0;12: }
c、使用itoa函数,使用方法类似于sprintf函数,函数原型:char *_itoa( int value, char *buffer, int radix ),
value表示要转换的整数,buffer存储转换后的字符串,radix是基数,也就是要转换成进制,一般是十进制,示例如下:
1: #include <iostream>2: #include <string>3: #include <sstream>4: using namespace std;5: int main(){6: int result=1000;7: char buffer[100];8: itoa(result,buffer,10);9: string str(buffer);10: cout<<str<<endl;11: return 0;12: }
d、使用宏定义,这个方法很灵活,也可以转换其他数据类型的数据,示例如下:
1: #include <iostream>2: #include <string>3: #define toString(x) #x4: using namespace std;5: int main(){6: int result=1000;7: string str=toString(result);8: cout<<str<<endl;9: return 0;10: }
以上所有的输出都是1000
2.string转int
a、使用stringstream对象,使用方法和int转string类似,示例如下所示:
1: #include <iostream>2: #include <string>3: #include <sstream>4: using namespace std;5: int main(){6: stringstream ss;7: string str="1000";8: int result;9: ss<<str;10: ss>>result;11: cout<<result<<endl;12: return 0;13: }
b、使用atoi函数,函数原型:int atoi ( const char * str ),使用这个函数之前必须先把string对象调用c_str()函数,
示例如下:
1: #include <iostream>2: #include <string>3: using namespace std;4: int main(){5: string str="1000";6: const char *pstr=str.c_str();7: int result=atoi(pstr);8: cout<<result<<endl;9: return 0;10: }
以上所有的输出都是1000。
本文所有示例程序都在vs2008下测试通过。