您的位置:首页 > 其它

字符数组、字符串、整型数之间的转化

2017-05-24 16:19 253 查看
1、字符数组 转化为 字符串

应用字符串定义时的构造函数

#include <iostream>
using namespace std;

//字符数组转化为字符串
#include <stdio.h>
#include <string.h>
int main()
{
char a[10];
scanf("%s",a);
string s(&a[0],&a[strlen(a)]);
cout<<s<<endl;
return 0;
}


2、字符串 转化为 字符数组

应用strncpy函数

#include <iostream>
using namespace std;

//字符串转化为字符数组
#include <string.h>
int main()
{
string s;
cin>>s;
char a[10];
strncpy(a,s.c_str(),s.length());
for(int i=0;i<10;i++)
cout<<a[i];
cout<<endl;
return 0;
}


3、数字型字符串转化为整型数

应用atoi函数

#include <iostream>
using namespace std;

//数字型字符串转化为整型数
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[10];
scanf("%s",a);
int x;
x=atoi(a);
cout<<x<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息