c++ 如何將string轉化int的方法


方法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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM