c++的atoi和stoi一些區別


c++的atoi和stoi一些區別

對c++標准庫中字符串轉化為int的兩個函數atoi()和stoi()兩個有所混亂,特地研究了一下。

stoi()

標准庫的函數默認模板

int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& 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.

意思是解析str的文本轉化為為int整數。
idx如果不為空,則會返回一個字符串中遇到的第一個字符(非數字)的字符下標,最后一個base是默認10進制。

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;
}

Output

2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3:  16579
-10010110001: -1201
0x7f: 127

atoi()

標准庫的函數默認模板

int atoi (const char * str);

標准庫中函數的解釋

Convert string to integer
Parses the C-string str interpreting its content as an integral number, which is returned as a value of type int.
The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many base-10 digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.

意思大概是解析字符串返回int。
首先會盡可能丟棄空格,直到找到一個第一個非空格字符,然后從這里開始,采用可選的初始加號和減號盡可能的10個數字來轉化。
字符串中包含數字外其他字符會被自動忽略。
只包含空格或者不是有效整數會返回空格。

注意

這個函數是c中傳到c++的,不會拋出異常,如果數組超出范圍,可能會導致未定義的行為。

總結

  • stoi用來轉哈string的,atoi轉化的是char[].
  • char[]轉string可以直接賦值或者用一個循環
  • string轉char
    • str.data()
    • str.c_str()
    • str.copy()
  • 個人感覺stoi的能力還是要比atoi的能力要大一些的,stoi可能往往要比atoi要好用。


免責聲明!

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



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