字符与字符串的转换
一、数字转换为字符数组
#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:/