创建一个atoi函数 [英] Creating an atoi function
问题描述
我正在尝试创建自己的atoi函数.通过以下操作,我得到的返回值为0.无论我在函数中更改数字变量如何,都将获得返回值.关于修改代码有什么建议吗?
I'm attempting to create my own atoi function. With the following I'm getting a return value of 0. Whatever I change the number variable within the function is what I get as a return value. Any suggestions on modifying the code?
//my atoi function
int atoi_me(char *numstring)
{
int number = 0;
while((*numstring >= '0') && (*numstring <= '9'))
{
number = (number * 10) + (*numstring - '0');
numstring++;
}
return number;
}
int main()
{
char *number[MAXSIZE];
int num;
printf("Please enter a number:\n");
scanf("%c", &number);
num = atoi_me(*number);
printf("%d", num);
return 0;
}
推荐答案
-
您要声明一个
char *
数组,即一个字符串数组,而不是单个字符串.您可能想要:
You're declaring an array of
char *
, that is, an array of strings, rather than a single string. You probably want:
char number[MAXSIZE];
您的scanf
格式字符串错误.如果要读取字符串,则应使用%s
. %c
仅读取一个字符.
Your scanf
format string is wrong. If you want to read a string, you should use %s
. %c
reads only a single character.
您的scanf
参数错误-传递number
本身(或者,如果愿意,可以传递&number[0]
),而不是&number
.
Your scanf
parameter is wrong - pass number
itself (or &number[0]
if you prefer), not &number
.
您要传递给atoi_me
的参数是错误的.用number
(或等效的&number[0]
)而不是*number
调用它.
The parameter you're passing to atoi_me
is wrong. Call it with number
(or equivalently &number[0]
), not *number
.
将所有内容放在一起,您应该有一个main
例程,如下所示:
Putting all of that together, you should have a main
routine something like this:
int main(void)
{
char number[MAXSIZE];
int num;
printf("Please enter a number: ");
scanf("%s", number);
num = atoi_me(number);
printf("%d\n", num);
return 0;
}
编者注:scanf
行可能会导致缓冲区溢出.您最好使用类似 fgets(3)
这样的函数,防范此类问题.
Editorial notes: You have a potential buffer overflow with the scanf
line. You'd be better off using a function like fgets(3)
that makes it easy to protect against that kind of problem.
atoi(3)
传统上也支持负数(前导-
)和可选的前导+
表示正数,而您的实现无法处理.
atoi(3)
also traditionally supports negative numbers (with a leading -
) and an optional leading +
for positive numbers, which your implementation doesn't handle.
这篇关于创建一个atoi函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!