如何检查输入的数字是否为正数?

How to check that inputed number is positive?

我只需要读取一个正数(unsigned long long),仅此而已,所以我使用scanf("%llu", &num);。但它也允许输入负值。
在这种情况下如何验证正数?用户必须在 [0..2^(64)-1] 中输入一个正数,但他可以在同一区间内错过并输入一个负值。但是我不能声明一个 long long 变量来检查它因为它可以包含 2^64 - 1 totally.

您可以使用 fgets() 将输入读入字符数组,检查第一个字符是否 -ve 符号 不是数字的字符然后使用 strtoull() 将其转换为 unsigned long long.

char c, buff[100];
fgets(buff, sizeof(buff), stdin);
//sscanf(buff, "%*[ ]%c", &c);
sscanf(buff, "%s", buff);
//if( (c<'0' || c>'9') )
if(buff[0]<'0' || buff[0]>'9')
{
     printf("\nNegative or invalid number!");
}
else
{
     num=strtoull(buff, NULL, 10);
}    

strtoull() 将 return ULLONG_MAX(在 limits.h 中定义)并将 errno 设置为 ERANGE(要使用这些,errno.h 头文件必须包含)如果 return 编辑的值不适合 unsigned long long.

if(num==ULLONG_MAX && errno==ERANGE)
{
    printf("\nOverflow");
}

sscanf()中的%*[ ]用于忽略字符串中前导的白色space。 第一个非 space 字符被找到并存储在 c 中,其值被检查。

here所述,sscanf(buff, "%s", buff); 将 trim 字符串 buff 两边的 space 去掉。

使用fgets(), then validate it, e.g. with strchr(). Finally use strtoull()将数字作为字符串读取以将字符串转换为数字,如果数字超出范围将失败:

If the value read is out of the range of representable values by an unsigned long long int, the function returns ULLONG_MAX (defined in <limits.h>), and errno is set to ERANGE.

示例:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
    char str[100]=;
    fgets(str, sizeof(str), stdin);
    str[strcspn(str, "\n")] = '[=10=]';

    if(strchr(str, '-') == NULL) {
        printf("Not a negative number\n");
        unsigned long long number = strtoull (str, NULL, 10);
        printf("%llu\n", number);
    } else {
        printf("Negative number\n");
    }

    return 0;
}

输出:

Not a negative number
12343566

对于-12343566,它给出:

Negative number