C++中将string类型转换为int, float, double类型 主要通过以下几种方式:

来源:互联网 发布:被收购的中国品牌 知乎 编辑:程序博客网 时间:2024/04/30 14:50

C++中将string类型转换为int, float, double类型 主要通过以下几种方式:

# 方法一: 使用stringstream

stringstream在int或float类型转换为string类型的方法中已经介绍过, 这里也能用作将string类型转换为常用的数值类型。

Demo:

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <sstream>    //使用stringstream需要引入这个头文件  
  3. using namespace std;  
  4.   
  5. //模板函数:将string类型变量转换为常用的数值类型(此方法具有普遍适用性)  
  6. template <class Type>  
  7. Type stringToNum(const string& str)  
  8. {  
  9.     istringstream iss(str);  
  10.     Type num;  
  11.     iss >> num;  
  12.     return num;      
  13. }  
  14.   
  15. int main(int argc, char* argv[])  
  16. {  
  17.     string str("00801");  
  18.     cout << stringToNum<int>(str) << endl;  
  19.   
  20.     system("pause");  
  21.     return 0;  
  22. }  

输出结果:

  801
 请按任意键继续. . .

  #方法二:使用atoi()、 atil() 、atof()函数  -----------------实际上是char类型向数值类型的转换

注意:使用 atoi 的话,如果 string s 为空,返回值为0.则无法判断s是0还是空

1. atoi():      int atoi ( const char * str );

说明:Parses the C string str interpreting its content as an integral number, which is returned as an int value.

参数:str : C string beginning with the representation of an integral number.

返回值:1. 成功转换显示一个Int类型的值.  2. 不可转换的字符串返回0.  3.如果转换后缓冲区溢出,返回 INT_MAXor INT_MIN

Demo:

[cpp] view plaincopy
  1. #include <iostream>  
  2. using namespace std;  
  3. int main ()  
  4. {  
  5.     int i;  
  6.     char szInput [256];  
  7.     cout<<"Enter a number: "<<endl;  
  8.     fgets ( szInput, 256, stdin );  
  9.     i = atoi (szInput);  
  10.     cout<<"The value entered is :"<<szInput<<endl;  
  11.     cout<<" The number convert is:"<<i<<endl;  
  12.     return 0;  
  13. }  

输出:

Enter a number: 48

The value entered is : 48

The number convert is: 48

2.aotl():  long int atol ( const char * str );

说明:C string str interpreting its content as an integral number, which is returned as a long int value(用法和atoi函数类似,返回值为long int)

3.atof():  double atof ( const char * str );

参数:C string beginning with the representation of a floating-point number.

返回值:1. 转换成功返回doublel类型的值 2.不能转换,返回0.0。  3.越界,返回HUGE_VAL

Demo:

[cpp] view plaincopy
  1. /* atof example: sine calculator */  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <math.h>  
  5. int main ()  
  6. {  
  7.   double n,m;  
  8.   double pi=3.1415926535;  
  9.   char szInput [256];  
  10.   printf ( "Enter degrees: " );  
  11.   gets ( szInput );  
  12.   //char类型转换为double类型   
  13.   n = atof ( szInput );  
  14.   m = sin (n*pi/180);  
  15.   printf ( "The sine of %f degrees is %f\n" , n, m );  
  16.     
  17.   return 0;  
  18. }  
0 0
原创粉丝点击