char [ ] 轉 float 或 double 範例一: char x[ ] = "25.34"; float a; double b; sscanf( x ,"%f" , &a); //float 用法 sscanf( x ,"%lf" , &b); //double 用法 cout << a << endl; cout << b << endl; 範例二:(此例不一定每一個 compiler 都可以) char x[ ] = "25.34"; float a; double b; a = atof(x); b = atof(x); cout << a << endl; cout << b << endl; string 轉 float 或 double 範例一: #include<sstream> string x = "25.34"; //char x[ ]="25.34"; 也可以 string t = "17.8"; //char t[ ] = "17.8"; 也可以 float a; double b; istringstream y(x); //建構方式讀取字串 y >> a; y.clear(); //buffer 必須清除才能讀取新的 y.str(t); //函數方式讀取字串 y >> b; cout << a << endl; cout << b << endl; 範例二: #include<sstream> string x = "25.34"; //char x[ ]="25.34"; 也可以 string t = "17.8"; //char t[ ] = "17.8"; 也可以 float a; double b; stringstream y(x); //建構方式讀取字串 y >> a; y.str(""); //兩道手續清空 buffer y.clear();//第二道手續 y << t; //重新導入新字串 y >> b; cout << a << endl; cout << b << endl; float 或 double 轉 char [ ] 範例一: #include <iostream> 或是 #include <stdio.h> char x[100]; float a = 2.571; double b = 31.79; sprintf( x , "%f", a ); //float 轉 char [ ] cout << x << endl; sprintf( x , "%lf", b ); //double 轉 char [ ] cout << x << endl; float 或 double 轉 string 範例一: #include<sstream> string x = ""; ostringstream y; float a = 2.571; double b = 31.79; y << a; //將 float 送到資料流 x = y.str(); cout << x << endl; y.str(""); //清空 buffer y << b; //將 double 送到資料流 x = y.str(); cout << x << endl; 範例二: #include<sstream> string x = ""; float a = 2.571; double b = 31.79; stringstream y; y << a; //將 float 送到資料流 y >> x; cout << x << endl; y.clear(); //清空 buffer y << b; //將 double 送到資料流 y >> x; cout << x << endl; |