編程小白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;
 } 

查看結果

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