编程小白C语言类型转换

字符串类型转基本数据类型

语法:通过<stdlib.h>的函数调用atoi atof即可

代码演示 

#include<stdio.h>
#include<stdlib.h>
int main()
{
	//字符数组 
	char str1[10]="123456";
	char str2[10]="12.67423";
	char str3[5]="abcd";
	char str4[4]="111";
	
	int num1 = atoi(str1); //atoi(str1)将str1转成整数 
	short s1 = atoi(str4);
	
	double d = atof(str2); //atof(str2)将str2转成小数 
	
	char c = str3[0]; // str3(0)表示获取到str3这个字符串(数组)的第一个元素 
	printf("num=%d d=%f c=%c s1=%d",num1,d,c,s1);
	return 0;
 } 

查看结果

注意事项 

在char数组类型转成基本数据类型时,要确保能够转成有效的数据,比如我们可以把"123"转成一个整数,但是不能把"hello"转成一个整数,如果格式不正确,会默认转成0或者0.0

案例演示

#include<stdio.h>
#include<stdlib.h>
int main()
{
	char str1[10]="hello";
	char str2[10]="hello";
	
	int a = atoi(str1); 
	
	double b = atof(str2); 
	 
	printf("str1=%s \nstr2=%s",a,b);
	return 0;
 } 

查看结果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章