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要好用。

posted on 2017-07-13 14:05  炮二平五  阅读(9337)  评论(0编辑  收藏  举报

导航