C++将string转为int

**

C++将string转为int

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

#include <iostream>
#include <sstream>    //引用stringstream的头文件
#include <string>

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;
}

在这里图片描述程序运行结果
Tips:由于stringstream不会主动释放内存,在多次使用stringstream时,会造成不必要的内存浪费,可使用ss.str(""),清空其占用的内存。

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

#include <iostream>
#include <string>

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;
}

在这里插入图片描述

#include <iostream>
#include <string>

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 <iostream>
#include <string>

using namespace std;

int main()
{
	string str = "a1b2c3";
	int i = str.at(1) - '0';
	cout << i << endl;
	return 0;
}
  • 16
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值