1. 程式人生 > >數字轉字串,字串轉數字

數字轉字串,字串轉數字

std::to_string
C++ Strings library std::basic_string
Defined in header

(1) std::string to_string( int value );
(2) std::string to_string( long value );
(3) std::string to_string( long long value );
(4) std::string to_string( unsigned value );
(5) std::string to_string( unsigned long value );
(6
) std::string to_string( unsigned long long value ); (7) std::string to_string( float value ); (8) std::string to_string( double value ); (9) std::string to_string( long double value );
#include <iostream>
#include <string>

int main()
{
    double f = 23.43;
    std::string f_str = std
::to_string(f); std::cout << f_str << '\n'; }
輸出:

23.430000
// to_string example  
#include <iostream>   // std::cout  
#include <string>     // std::string, std::to_string  

int main ()  
{  
  std::string pi = "pi is " + std::to_string(3.1415926);  
  std::string perfect = std
::to_string(1+2+4+7+14) + " is a perfect number"; std::cout << pi << '\n'; std::cout << perfect << '\n'; return 0; }
pi is 3.141593  
28 is a perfect number  

二、string轉int
1.可以使用std::stoi/stol/stoll等等函式
Example:

// stoi example  
#include <iostream>   // std::cout  
#include <string>     // std::string, std::stoi  

int main ()  
{  
  std::string str_dec = "2001, A Space Odyssey";  
  std::string str_hex = "40c3";  
  std::string str_bin = "-10010110001";  
  std::string str_auto = "0x7f";  

  std::string::size_type sz;   // alias of size_t  

  int i_dec = std::stoi (str_dec,&sz);  
  int i_hex = std::stoi (str_hex,nullptr,16);  
  int i_bin = std::stoi (str_bin,nullptr,2);  
  int i_auto = std::stoi (str_auto,nullptr,0);  

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";  
  std::cout << str_hex << ": " << i_hex << '\n';  
  std::cout << str_bin << ": " << i_bin << '\n';  
  std::cout << str_auto << ": " << i_auto << '\n';  

  return 0;  
} 
2001, A Space Odyssey: 2001 and [, A Space Odyssey]  
40c3:  16579  
-10010110001: -1201  
0x7f: 127  
string s = "12";   
int a = atoi(s.c_str());  

首先atoi和strtol都是c裡面的函式,他們都可以將字串轉為int,它們的引數都是const char*,因此在用string時,必須調c_str()方法將其轉為char*的字串。或者atof,strtod將字串轉為double,它們都從字串開始尋找數字或者正負號或者小數點,然後遇到非法字元終止,不會報異常:

int main() {
    using namespace std;
    string strnum=" 232s3112";
    int num1=atoi(strnum.c_str());
    long int num2=strtol(strnum.c_str(),nullptr,10);
    cout<<"atoi的結果為:"<<num1<<endl;
    cout<<"strtol的結果為:"<<num2<<endl;
    return 0;
}
atoi的結果為:232
strtol的結果為:232

可以看到,程式在最開始遇到空格跳過,然後遇到了字元’s’終止,最後返回了232。

這裡要補充的是strtol的第三個引數base的含義是當前字串中的數字是什麼進位制,而atoi則只能識別十進位制的。例如:

using namespace std;
    string strnum="0XDEADbeE";
    int num1=atoi(strnum.c_str());
    long int num2=strtol(strnum.c_str(),nullptr,16);
    cout<<"atoi的結果為:"<<num1<<endl;
    cout<<"strtol的結果為:"<<num2<<endl;
    return 0;
atoi的結果為:0
strtol的結果為:233495534