C++中将string類型轉換為int, float, double類型 主要通過以下幾種方式:
# 方法一: 使用stringstream
stringstream在int或float類型轉換為string類型的方法中已經介紹過, 這裡也能用作将string類型轉換為常用的數值類型。
Demo:
#include <iostream>
#include <sstream> //使用stringstream需要引入這個頭檔案
using namespace std;
//模闆函數:将string類型變量轉換為常用的數值類型(此方法具有普遍适用性)
template <class Type>
Type stringToNum(const string& str)
{
istringstream iss(str);
Type num;
iss >> num;
return num;
}
int main(int argc, char* argv[])
{
string str("00801");
cout << stringToNum<int>(str) << endl;
system("pause");
return 0;
}
輸出結果:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiclRnblN0LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX90TUPdXU610MJpWT4FEVkZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DM0kDNyMjMzIDMyQDM1EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
#方法二:使用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_MAX orINT_MIN
Demo:
#include <iostream>
using namespace std;
int main ()
{
int i;
char szInput [256];
cout<<"Enter a number: "<<endl;
fgets ( szInput, 256, stdin );
i = atoi (szInput);
cout<<"The value entered is :"<<szInput<<endl;
cout<<" The number convert is:"<<i<<endl;
return 0;
}
輸出:
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:
/* atof example: sine calculator */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main ()
{
double n,m;
double pi=3.1415926535;
char szInput [256];
printf ( "Enter degrees: " );
gets ( szInput );
//char類型轉換為double類型
n = atof ( szInput );
m = sin (n*pi/180);
printf ( "The sine of %f degrees is %f\n" , n, m );
return 0;
}