gpt4 book ai didi

c - 使用 atoi() 对整数进行输入验证

转载 作者:行者123 更新时间:2023-11-30 16:21:09 25 4
gpt4 key购买 nike

#include "stdafx.h"
#include <stdlib.h>

void main()
{
char buffer[20];
int num;

printf("Please enter a number\n");
fgets(buffer, 20, stdin);
num = atoi(buffer);

if(num == '\0')
{
printf("Error Message!");
}

else
{
printf("\n\nThe number entered is %d", num);
}

getchar();
}

上面的代码接受字符串形式的数字,并使用atoi将其转换为整数。如果用户输入小数,则仅接受小数点之前的位。而且,如果用户输入字母,则返回0。

现在,我有两个疑问:

i) 我希望程序检测用户是否输入了带小数点的数字并输出错误消息。我不希望它取小数点之前的部分。我希望它识别出输入无效。

ii) 如果 atoi 在有字母的情况下返回 0,那么我如何验证它,因为用户也可以输入数字 0?

谢谢。

最佳答案

atoi 不适合错误检查。请改用 strtolstrtoul

#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>

long int result;
char *pend;

errno = 0;
result = strtol (buffer, &pend, 10);

if (result == LONG_MIN && errno != 0)
{
/* Underflow. */
}

if (result == LONG_MAX && errno != 0)
{
/* Overflow. */
}

if (*pend != '\0')
{
/* Integer followed by some stuff (floating-point number for instance). */
}

关于c - 使用 atoi() 对整数进行输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com