string与int的相互转换

有4种方法:

  1. stringstream
  2. atoi/itoa
  3. sscanf/sprintf
  4. lexical_cast

###1.stringstream
头文件:#include <sstream>

stringstream继承关系


####1.1 string to int
下面的例子将输入到str中的字符通过string stream类型的变量ss转换为int类型的变量,输入到num中:

stringstream ss;
string str;
int num;
cin>>str;

ss<<str;//或者ss.str(str);
ss>>num;
cout<<num;

更进一步,str中可以包含多个数字,如“11 22 33”,并且需要重复利用stringstream类型变量时,要使用clear()成员函数清除状态,并且使用str("")清除内存:

stringstream ss;
int num, times;//times是使用ss的次数
string str;

cout<<"Please enter string lines:";
cin>>times;
getline(cin, str);// 读取换行
for(int i= 0; i < times; i++) {
	//str可以包含多个数字,如“11 22 33”
	getline(cin, str);
	ss.str(str);//也可以使用ss<<str;
	while(!ss.eof()) {
		ss>>num;
		cout<<num<<endl;			
	}
	ss.clear();//清空状态
	ss.str("");//清空内存
}

运行结果:

Please enter string lines:1
11 22 33
11
22
33
请按任意键继续. . .

PS:
1、如果只使用ss.clear(), 未使用ss.str(""); 则只清除了状态,并没有清除内存,则在使用ss<<str的情况下,ss将一直保存着所有str的内容。ss.str(str)不会出现这样的内容,因为ss.str(str)相当于直接从将ss的buffer部分赋值为str。(如果出错请指正)
2、如果只使用ss.str(""), 则只是清除了内存,并没有清除状态,所以在第二次使用ss转换字符串时,ss的状态仍然是ios::eofbit状态,所以不能将str的值>>到num中。
3、ss的状态包含:

gootbit:无错误
eofbit:已到达文件尾
failbit:非致命输入/输出命令,可挽回
badbit:致命输入/输出命令,不可挽回

可以使用ss.rdstate()获取到ss的状态,或者ss.good(), ss.eof(), ss.fail(), ss.bad()
4、 使用模板转换任意类型:

template<class output_type, class input_type>
output_type convert(const input_type &t)
{
	stringstream ss;
	output_type result;
	ss<<t;
	ss>>result;
	return result;
}

使用convert():

double doub = 1.11;
string str;
str = convert<string>(doub);

####1.2 int to string
与string to int相类似:

string str;
stringstream ss;
int num;
cin>>num;

ss<<num;
ss>>str;
cout<<str<<endl;

参考文章:

  1. http://www.cplusplus.com/reference/sstream/stringstream/

###2. atoi/itoa

####2.1 string to int
函数:int atoi(const char *str)
功能:忽略空白字符,一直到第一个非空白字符,可选的接收“+”或“-”字符,接下来是base为10的各个digits,然后把其转换为整数,不是digit的字符会被忽略,并结束转换。
返回值:成功返回int数值,如果int占4个字节,该值的范围为-231~231,如果超出了int的范围,导致undefined behavior错误。

使用atoi:

int num; 
string str;
cin>>str;
num = atoi(str.c_str());

更进一步,可以使用函数strtol()

函数:long int strtol(const char *str, char ** endptr, int base)
作用:将str转换为long int类型的数
参数:str表示整数的字符串;endptr为指针指向char*,char *设置为str中数值的下一个字符,可以将该字段设置为NULL,表示不使用;base为numerical base,用于指明str的base,如果该值为0,则base根据字符串决定,如0xaa
返回值:转换成功,返回long int类型数值;如果是没有成功,返回0值(0L);如果数值的范围超过long int范围,返回LONG_MAX/LONG_MIN(defined in <climits>),并且 errno设置为 ERANGE

Example:

string str("2001 60c0c0 -1101110100110100100000 0x6fffff");
char * pEnd;
long int li1, li2, li3, li4;
li1 = strtol (str.c_str(),&pEnd,10);
li2 = strtol (pEnd,&pEnd,16);
li3 = strtol (pEnd,&pEnd,2);
li4 = strtol (pEnd,NULL,0);
printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);

output:

The decimal equivalents are: 2001, 6340800, -3624224 and 7340031


####2.2 int to string
函数:char * itoa ( int value, char * str, int base )
作用:将value的值,以base为参照,转换为字符串,str指向该字符串。
与string to int相类似:

//不知道怎么使用string, 有点问题:c[8]中可能存不下
char c[8];
int num;
cin>>num;
itoa(num,c,16);
cout<<c<<endl; // 1e

参考文章:

  1. http://www.cplusplus.com/reference/cstdlib/atoi/
  2. http://www.cplusplus.com/reference/cstdlib/itoa/

###3. sscanf/sprintf

####3.1 string to int
函数:int sscanf ( const char * s, const char * format, ...)

string str("11");
int num;
sscanf(str.c_str(),"%x",&num);//字符串为16进制,所以0x11为17
cout<<num<<endl;

output:

17


####3.2 int to string
函数:int sprintf ( char * str, const char * format, ... )
返回值:返回写入字符串的长度。

int num = 12;
char str[20];
sprintf(str,"%04x",num);
cout<<str<<endl;

output:

000c

参考文章:
1、http://www.cplusplus.com/reference/cstdio/sprintf/
2、http://www.cplusplus.com/reference/cstdio/sscanf/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值