字符与字符串的转换

字符与字符串的转换

一、数字转换为字符数组
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int num =9;
char str[25];
itoa(num,str, 10);
printf(“The nmber ‘num’ is %d and the string ‘str’ is %s. \n”,
num,str);
return 0;
}
在这里插入图片描述
二、字符串字符数组转换为数字
#include
#include
using namespace std;

int main()
{
const char *str1=“12”;
const char *str2=“3.1415”;
const char *str3=“333”;

int num1 = atoi (str1);
int num2 = atoi (str2);
int num3 = atoi (str3);

cout<<"atoi(\"" << str1
       << "\") is " <<num1 <<'\n';
cout<<"atoi(\"" << str2
       << "\") is " <<num2<<'\n';	   
cout<<"atoi(\"" << str3
       << "\") is " <<num3 <<'\n';	   
	   
return 0;	    

}

直接输入1次#在这里插入图片描述
三、字符数组转换成字符串
#include
#include
using namespace std;
int main ()
{
char str[5]={‘w’,‘o’,‘r’,‘d’};
string k(str);
cout<<k<<endl;
return 0;
}
在这里插入图片描述

四、字符串转换成字符数组
#include
#include
#include
#include
using namespace std;
int main()
{
string s=“哈哈哈哈”;
char str1[5];
strcpy(str1,s.c_str());
printf("%s\n",str1);

char str2[5];
strcpy(str2,s.c_str());
printf("%s\n",str2); 

return 0;

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7oZ7IMMF-1615730934043)(https:/在这里插入图片描述

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值