C++ int和string类型互转实用方法汇总
1、int 转 string
使用到头文件#include<sstream>中的stringstream,
#include <sstream> #include <iostream> using namespace std; int main() { int i = 45634535; stringstream ss; ss << i;//int值传给stringstream string out_string = ss.str();//stringstream转string类型 cout << out_string << " "; return 0; }
注意的是:stringstream类型变量,不能自动释放内存,多次用到时,最好要配合.clear(); 主动释放内存。
2、string 转 int
方法1.
通过stringstream作为中间体,实现string转int
#include <iostream> #include <sstream> using namespace std; int main() { int x; string str = "-10"; string str1 = "10"; stringstream ss; ss << str;//string转stringstream ss >> x;//stringstream转int cout << x << endl; ss.clear(); //多次使用stringstream时,这段程序不能省略! ss << str1; ss >> x; cout << x << endl; return 0; }
Tips:由于stringstream不会主动释放内存,在多次使用stringstream时,会造成不必要的内存浪费,可使用ss.str(""),清空其占用的内存
方法2.
用到C语言中的方法atoi(字符串首地址),其头文件为#include <cstdlib>,它的功能是将字符串转成int类型,注意的是,它的参数类型要求为字符串首地址,所以对于string类型,不能直接把变量放进去,而是要用到string方法c_str()f返回其首字符地址。
#include <iostream> #include <cstdlib> using namespace std; int main() { int x; string str = "-10"; string str1 = "-10agdgd"; string str2 = "da10"; x = atoi(str.c_str());//返回首地址 cout << x << endl; x = atoi(str1.c_str()); //atoi()函数遇到字母时会自动停下 cout << x << endl; x = atoi(str2.c_str()); //atoi()函数转,字符串首字母不为数字时,输出为0 cout << x << endl; }