Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1251626
  • 博文数量: 247
  • 博客积分: 5587
  • 博客等级: 大校
  • 技术积分: 2060
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-24 13:27
文章分类
文章存档

2012年(101)

2011年(44)

2010年(102)

分类: 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;
} 
阅读(726) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-09-06 14:40:50

Download More than 1000 free IT eBooks: http://free-ebooks.appspot.com