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