C语言中字符串和字符数组以及实数的相互转换

int main(){
     
	//char数组可自动转化为字符串,可直接赋值 
	char ch[20] = " jakjfdkajkfljafsn";
	string s = ch;
	cout << s << endl;
	//字符串化成char数组,c_str()返回该字符串的首地址 
	printf("%s\n",s.c_str());  
	//数字化成字符串 
	stringstream sstr;
	double x = 126.8932;
	sstr << x;
	s = sstr.str();
	cout << s + "jakf"<< endl;
	// char数组化数字
	char ch2[20] = "-12345.783";
	char ch1[20] = "326";
	double a1 = atof(ch2) + atoi(ch1);
	printf("%lf\n", a1);
	char*itoa(int value,char*string,int radix);
	//itoa与atoi功能相反,int value 被转换的整数,char *string 转换后储存的字符数组,int radix 转换进制数,如2,8,10,16 进制等
	int number=156;
	char str[10];
	itoa(number,str,16);
	printf("%s\n", str);
	//格式化字符串
	char str1[10] = "1234" ;
	int i;
	sscanf(str1, "%d", &i); // 将字符串转换成整数 i 
	printf("%d\n", i+2);
	int data = 789;
	sprintf(str1,"%d",data);//将data转换为字符串
	cout <<  str1 << endl;
	char str2[10] = "10";
	sprintf(str1,"%s and %s\n",str1, str2); //连接字符串 
	cout << str1 <<endl;
}

你可能感兴趣的:(c语言)