方法1
在C
標准庫里面,使用atoi(表示 ascii to integer)
是把字符串轉換成整型數的一個函數int atoi(const char *nptr)
方法2
在C++
標准庫里面,使用stringstream:
(stringstream
可以用於各種數據類型之間的轉換)。
例子:
#include <sstream>
#include <string>
std::string text = "152";
int number;
std::stringstream ss;
ss << text;//可以是其他數據類型
ss >> number; //string -> int
方法3
int stoi (const string& str, size_t* idx = 0, int base = 10);
Parses str interpreting its content as an integral number of the specified base,
which is returned as an int value.If idx is not a null pointer,
the function also sets the value of idx to the position of the first character
in str after the number.
題外話
反問,在C++
中,如何將數值類型轉換為string
類型呢?
std::to_string
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Convert numerical value to string,Returns a string with the representation
of val.