C++将string转为int

**

C++将string转为int

**
方法一:使用stringstream(流的输入输出操作实现)

#include 
#include     //引用stringstream的头文件
#include 

using namespace std;

int main()
{
	int x;
	string str = "-10";
	string str1 = "10";
	stringstream ss;
	ss << str;
	ss >> x;
	cout << x << endl;
	ss.clear();    //多次使用stringstream时,这段程序不能省略!
	ss << str1;
	ss >> x;
	cout << x << endl;
}

C++将string转为int_第1张图片程序运行结果
Tips:由于stringstream不会主动释放内存,在多次使用stringstream时,会造成不必要的内存浪费,可使用ss.str(""),清空其占用的内存。

方法二:使用atoi函数或stoi()函数

#include 
#include 

using namespace std;

int main()
{
	int x;
	string str = "-10";
	string str1 = "-10a";
	string str2 = "a10";
	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;
	return 0;
}

C++将string转为int_第2张图片

#include 
#include 

using namespace std;

int main()
{
	int x;
	string str = "-10";
	string str1 = "-10a";
	string str2 = "a10";
	x = stoi(str);
	cout << x << endl;
	x = stoi(str1);		 //stoi()函数遇到字母时会自动停下
	cout << x << endl;
	//x = stoi(str2);    //stoi()函数没有数字的话,程序虽然可以编译,但运行时会出错
	//cout << x << endl;
	return 0;
}

方法三:使用at()函数定位,先转为字符型,然后再转为int类型

#include 
#include 

using namespace std;

int main()
{
	string str = "a1b2c3";
	int i = str.at(1) - '0';
	cout << i << endl;
	return 0;
}

你可能感兴趣的:(C++)