您的位置:首页 > 其它

字符串字符数组和基本类型的相互转换

2015-03-05 14:51 465 查看

1.基本类型转为字符数组或字符串

❶整形转为字符数组: char *itoa(int value, char *string, int radix);

value  将要被转换的值。
string  转换的结果存储位置
radix   Base of value; must be in the range 2-36(转换基数,例如:radix=10表示10进制,radix=8表示8进制。)
返回值:与string参数相同,便于函数的嵌套调用

倘若要获得字符串,使用string(char*)的构造函数即可以获得字符串。

❷浮点型转为字符数组或者字符串

比较简单的方法。使用字符串流。

stringstream ss;
string c;
char d[10];
ss<<14.20;
ss>>c;//转为字符串;
strcpy(d,ss.str().c_str());//转为字符数组
cout<<c<<endl;
cout<<d<<endl;


注意: strcpy的第二个参数必须为常量指针const char*。故必须使用ss.str().c-str()获得,返回的是指向值为常量的指针const char*类型。

2.字符数组或字符串转为基本类型

❶字符数组转为基本类型。atoi, atof,atol(C++11标准库, "stdlib.h") 函数将字符数组转换成int,double, long变量,如

  char  str[] = "15.455";
  double db;
  int i;
  db = atof(str);   // db = 15.455
  i = atoi(str);    // i = 15


  ❷字符串(string类型)转为基本类型。要用c_str()方法获取其字符数组指针char*,然后调用上述的方法。如下:

  string  str = "15.455";
  double db;
  int i;
  db = atof(str.c_str());// db = 15.455
  i = atoi(str.c_str());// i = 15


3.字符串流sstream

❶实际上,stringstream可以读入基本类型和字符串字符数组。然后使用>>输出到int,double,string和字符数组中等类型。即,可以完成任意两两之间的转换。例如:

stringstream ss;
string c("13.40");
double dValue=0.0;
int intValue=0;
char d[10]={'1','3','.','4','0'};
ss<<d;//或者ss<<c;
ss>>intValue;
ss>>dValue;
不管是输入字符数组d还是字符串c。得到的结果都是intValue=13和dValue=0.40。当然,倘若交换读入顺序,如

ss>>dValue;
ss>>intValue;
则dValue=13.40而intValue为随机数。

❷但是,有一点要注意。倘若要循环读入字符,且清除原始的内容,应该使用ss.str("")。如下,寻找小于100的数中,含有5和6的数的个数。

#include"iostream"
#include "sstream"
#include "stdlib.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char s[5];memset(s,0,sizeof(s));
int sum;

for(int i=0,sum=0;i<100;i++)
if(strchr(itoa(i,s,10),'5')&&strchr(s,'6'))
cout<<sum++<<": "<<i<<endl;

stringstream ss;
for(int i=0,sum=0;i<100;i++)
{
ss.str(""); ss<<i;//清除
strcpy(s,ss.str().c_str());//获得数组
if(strchr(s,'5')&&strchr(s,'6'))
cout<<sum++<<"  "<<i<<endl;
}

return 0;
}
输出相同
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: