目录
函数原型:
int atoi(const char* str);
所属头文件:stdlib.h
一、函数说明
将字符串转换为整数(Convert string to integer)。
-
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.
int isspace(int c);
所属头文件:
ctype.h
函数说明:检查
c
是否为空白字符(Checks whetherc
is a white-space character)。空白字符可以是下面中的任意字符:空白字符 十进制 意义 ' ' 32 空格(space) '\t' 9 水平制表符(horizontal tab) '\n' 10 换行(newline) '\v' 11 垂直制表符(vertical tab) '\f' 12 换页(form feed) '\r' 13 回车(carriage return) 返回值:如果
c
确实是一个空白字符,则返回一个非零值,即 true;否则,返回零,即 false。 -
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 eitherstr
is empty or it contains only whitespace characters, no conversion is performed and zero is returned.如果
str
中的第一个非空白字符序列不是有效的整数,或者由于str
为空或仅包含空白字符而不存在此类序列,则不执行转换并返回零。
二、返回值
On success, the function returns the converted integral number as an
int
value.
成功后,该函数将转换后的整数作为 int
值返回。
If the converted value would be out of the range of representable values by an
int
, it causes undefined behavior.
如果转换后的值超出 int
的可表示值范围,则会导致未定义的行为。
三、模拟实现
int my_atoi(const char* str)
{
assert(str);
typedef enum Sign
{
NEGTIVE = -1,
POSITIVE = 1
}Sign;
// 首先跳过空白字符
while (isspace(*str))
{
str++;
}
// 然后根据第一个非空白字符确定正负号
Sign flag = POSITIVE; // 默认为正号
if (*str == '+')
{
str++;
}
else if (*str == '-')
{
flag = NEGTIVE;
str++;
}
// 确定返回值并返回
int ret = 0;
while (*str >= '0' && *str <= '9')
{
ret = ret * 10 + flag * (*str - '0');
str++;
}
return ret;
}