#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> using namespace std; void int2str(const int &int_temp, string &string_temp) { char s[12]; //设定12位对于存储32位int值足够 _itoa(int_temp, s, 10); //itoa函数亦可以实现,但是属于C中函数,在C++中推荐用流的方法 string_temp = s; } void main() { int a = 60; string str1 = "100"; int2str(a,str1); cout << str1 << endl; string str2 = "278"; int b = atoi(str2.c_str()); cout << "b is " << b << endl; }
cout<< string类型时,要用头文件 <string>,和命名空间std.
2, CString、string和string.h这几个区别:
CSting:CString是MFC或者ATL中的实现,是MFC里面封装的一个关于字符串处理的功能很强大的类,只有支持MFC的工程才可以使用。在MFC中使用不需要自己加,但在另外的程序中需要加入#include<CString>。
string:string类既是一个标准c++的类库,同时也是STL(Standard Template Library,标准模版库)中的类库,已经纳入C++标准之中。它和CString有本质的区别。
string.h:C语言里面关于字符数组的函数定义的头文件,常用函数有strlen、strcmp、strcpy等等,这个头文件跟C++的string类半点关系也没有,所以 <string>并非 <string.h>的“升级版本”,他们是毫无关系的两个头文件。