c++字符串与数字之间的转换

查看数据类型:

使用条件

#include<typeinfo>

语法

typeid(数据).name();

示例

#include<iostream>
#include<typeinfo>
#include<string>
using namespace std;
int main() {
	int num1 = 123456;
	string s1 = "abc";
	cout << typeid(s1).name()<<endl;
	cout << typeid(num1).name();
	
	return 0;
}

__________________________________
Visual Studio运行结果
class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
int

DEV运行结果
Ss
i

可以看出编辑器的不同,运行的结果也不相同。

Visual Studio用的是自己内嵌的微软编辑器,做了优化,更加人性化。而dev用的是gcc编辑器,这个编辑器很经典。在Visual Studio可以直接看出数据的类型,gcc的数据类型对应如下:

bool:                     b
 
char:                     c
signed char:              a
unsigned char:            h
 
(signed) short (int):     s
unsigned short (int):     t
 
(signed) (int):           i
unsigned (int):           j
 
(signed) long (int):      l
unsigned long (int):      m
 
(signed) long long (int): x
unsigned long long (int): y
 
float:                     f
double:                   d

string:					  Ss

字符串转数字

1.stoi、stof、stod、stol、stoll

string str("12345");
int num=stoi(str);
cout<<num<<endl;
cout<<typeid(num).name()<<endl; //i int类型

2.stringstream

使用stringstream需要引用sstream头文件。

string str="123";
int num;
stringstream ss;
ss<<str;
ss>>num;
cout<<num<<endl;
cout<<typeid(num).name()<<endl;//i

数字转字符串

1.to_string

int num=123;
string str=to_string(num);
cout<<str<<endl;
cout<<typeid(str).name()<<endl;//Ss	string类型

2.stringstream

使用stringstream需要引用sstream头文件。

stringstream ss;
string str;
int num=123;
ss<<num;
ss>>str;
cout<<str<<endl;	//123
cout<<typeid(str).name()<<endl;	//Ss
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值