分类: C/C++
2010-09-04 12:43:12
atof()将字符串转换成实数 atoi()将字符串转换成整数 itoa()将整数转换成字符串 ftoa()将实数转换成字符串 布尔值只有1和0,要转换的应该只有和整数一样
用string流,直接转换 #include#include #include using namespace std; void ValToArray() { double x= 43.435; int y = 3434; bool z = true; stringstream ss; char str[100]; ss << x; ss >> str; cout << str << endl; ss.sync(); ss.clear(); ss << y; ss >> str; cout << str << endl; ss.sync(); ss.clear(); ss << z; ss >> str; cout << str << endl; } void ArrayToVal() { string s; bool flag = 0; cout << "input a number string: "; cin >> s; for(string::iterator it = s.begin(); it != s.end(); it++) { if((*it < '0' || * it > '9') && *it != '.') { cout << "invalid input !" << endl; return; } if(*it == '.') flag = 1; } stringstream ss; if(flag) { cout << "the val is double: "; double x; ss.str(s); ss >> x; cout << x << endl; } else { cout << "the val is int: "; int y; ss.str(s); ss >> y; cout << y << endl; } } int main() { ValToArray(); //变量转字符串 cout << endl; ArrayToVal(); //字符串转变量 return 0; }
chinaunix网友2010-09-06 14:40:50
Download More than 1000 free IT eBooks: http://free-ebooks.appspot.com