atoi
函数是 C 语言标准库中的一个函数,用于将字符串转换为整数。其原型如下:
int atoi(const char *str);
atoi
函数的主要功能是将一个表示数字的字符串转换为一个整数。它会忽略字符串前面的空白字符(如空格、制表符等),直到遇到数字或正负号开始转换,直到遇到非数字字符为止。
以下是一个简单的 atoi
函数的实现示例:
#include <stdio.h>
#include <ctype.h>
int my_atoi(const char *str) {
int result = 0;
int sign = 1;
int i = 0;
// Skip leading whitespace
while (isspace(str[i])) {
i++;
}
// Handle sign
if (str[i] == '-') {
sign = -1;
i++;
} else if (str[i] == '+') {
i++;
}
// Convert digits and ignore other characters
while (isdigit(str[i])) {
result = result * 10 + (str[i] - '0');
i++;
}
return result * sign;
}
int main() {
const char *test_str = " -123abc";
int num = my_atoi(test_str);
printf("Converted number: %d\n", num); // Output: -123
return 0;
}
atoi
函数的使用非常简单,只需传入一个字符串即可。atoi
函数。atoi
函数返回的是一个 int
类型的整数。需要注意的是,atoi
函数在处理大数时可能会溢出,因为它没有检查转换后的数值是否在 int
类型的范围内。
atoi
函数常用于从配置文件、用户输入或其他文本数据中提取整数值。例如:
int
类型的范围,atoi
函数会返回一个不确定的值。可以使用 strtol
函数来代替 atoi
,因为它可以处理更大的数值范围,并且可以检查溢出。#include <stdio.h>
#include <stdlib.h>
int main() {
const char *test_str = "2147483648"; // 超出 int 范围
char *endptr;
long num = strtol(test_str, &endptr, 10);
if (endptr == test_str || *endptr != '\0') {
printf("Invalid input\n");
} else if (num > INT_MAX || num < INT_MIN) {
printf("Overflow or underflow\n");
} else {
printf("Converted number: %d\n", (int)num);
}
return 0;
}
atoi
函数会停止转换并忽略后面的字符。可以使用 strtol
函数来获取更详细的错误信息。#include <stdio.h>
#include <stdlib.h>
int main() {
const char *test_str = "123abc";
char *endptr;
long num = strtol(test_str, &endptr, 10);
if (endptr == test_str || *endptr != '\0') {
printf("Invalid input: %s\n", endptr);
} else {
printf("Converted number: %ld\n", num);
}
return 0;
}
通过以上内容,你应该对 atoi
函数有了更深入的了解,并且知道如何处理可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云