字符串和数字的转换

int转char*


使用_itoa(int,char*,int)//要转的数字,字符串,进制
int main()
{
	int num1 = 123;
	int num2 = 456;
	char str[10];
	char *temp = _itoa(num1,str,10);

	printf("str=%s",str);
	printf("temp=%s",temp);
	system("pause");
	return 0;
}

char*转int

使用atoi(char*)//字符串,返回值是转之后的int

```cpp
int main()
{	
	char *str = "123456";
	int temp = atoi(str);
	printf("temp=%d",temp);

	system("pause");
	return 0;
}

int转string


```cpp
#include<iostream>
using namespace std;
#include<sstream>
int main()
{	
	int num1 = 123;
	string str;
	stringstream ss;
	ss<<num1;
	ss>>str;
	cout<<str;
	system("pause");
	return 0;
}

string转int

#include<iostream>
using namespace std;
#include<sstream>
int main()
{	
	int num1 ;
	string str = "123456";
	stringstream ss;
	ss<<str;
	ss>>num1;
	cout<<num1;
	system("pause");
	return 0;
}

string转char*

string可以被看成是以字符为元素的一种容器。字符构成序列(字符串)。有时候在字符序列中进行遍历,标准的string类提供了STL容器接口。具有一些成员函数比如begin()、end(),迭代器可以根据他们进行定位。
注意,与char不同的是,string不一定以NULL(’\0’)结束。string长度可以根据length()得到,string可以根据下标访问。所以,不能将string直接赋值给char

#include<iostream>
using namespace std;
#include<sstream>
int main()
{	
	string str = "hello";
	const char* temp = str.c_str();
	cout<<temp;
	
	system("pause");
	return 0;
}

char*转string

printf只能输出C语言内置的数据,而string不是内置的,只是一个扩展的类

#include<iostream>
using namespace std;
#include<sstream>
int main()
{	
	char *temp = "hello" ;
	string str ;
	str = temp;
	cout<<str;//可以直接输出hello
	printf("%s",str.c_str());//需要使用c_str()变成char*
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值