int atoi( const char *str );
官方解释:
Interprets an integer value in a byte string pointed to by
str
.Discards any whitespace characters until the first non-whitespace character is found, then takes as many characters as possible to form a valid integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
- (optional) plus or minus sign
- numeric digits
Parameters
str
- pointer to the null-terminated byte string to be interpretedReturn value
Integer value corresponding to the contents of
str
on success. If the converted value falls out of range of corresponding return type, the return value is undefined. If no conversion can be performed,0
is returned.
先说明下当atoi的输入为nullptr,会Segmentation fault
下面举几个例子
#include <iostream>
#include <cstdlib>
#include <string>
int main()
{
const char *str1 = "42";
const char *str2 = "3.14159";
const char *str3 = "31337 with words";
const char *str4 = "words and 2";
std::string str5 = "-122";
int num1 = std::atoi(str1);
int num2 = std::atoi(str2);
int num3 = std::atoi(str3);
int num4 = std::atoi(str4);
int num5 = std::atoi(str5.c_str());
std::cout << "std::atoi(\"" << str1 << "\") is " << num1 << '\n';
std::cout << "std::atoi(\"" << str2 << "\") is " << num2 << '\n';
std::cout << "std::atoi(\"" << str3 << "\") is " << num3 << '\n';
std::cout << "std::atoi(\"" << str4 << "\") is " << num4 << '\n';
std::cout << "std::atoi(\"" << str5 << "\") is " << num5 << '\n';
}
// output
std::atoi("42") is 42
std::atoi("3.14159") is 3
std::atoi("31337 with words") is 31337
std::atoi("words and 2") is 0
std::atoi("-122") is -122
上述例子将所有字符串进行转换,若只转换字符串中的一部分,可能就需要考虑越界的情况,当然下面的例子是通过(point+index)的方式进行输入的,若直接通过c_str()可无视。
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "12345678";
char *ch = const_cast<char *>(str.c_str());
int num1 = atoi(ch + 2);
int num2 = atoi(ch + 5);
int num3 = atoi(ch + 25); // maybe Segmentation fault
cout << "num1 : " << num1 << endl;
cout << "num2 : " << num2 << endl;
cout << "num3 : " << num3 << endl;
cout << "ch1 : " << ch + 2 << endl;
cout << "ch2 : " << ch + 5 << endl;
cout << "ch3 : " << ch + 25 << endl;
}
// output
num1 : 345678
num2 : 678
num3 : 0
ch1 : 345678
ch2 : 678
ch3 : @
在11行可能会出现Segmentation fault的问题,小概率事件,在19行的打印信息中可以看出,输出的信息是随的,有可能就执行了nullptr,就出现了Segmentation fault