简体   繁体   English

C,添加语句以检查输入是否为 integer

[英]C, add statement to check if input is an integer

This is currently what I have, I want to add a statement at the bottom that prints printf("Error");这就是我目前所拥有的,我想在底部添加一个打印printf("Error");的语句if the data entered isn't a number.如果输入的数据不是数字。

int main() {
    long long number;
    long long ret;
    
    printf("Enter a number between [0 - 4294967295]: ");
    scanf("%lld", &number);
    
    printf("Number is %lld\n", number);
    //if statements to see if number is above/below the range
    if (number < 0) {
        printf("Error: This number is below the range.");
        return -1;
    }
    if (number > 4294967295) {
        printf("Error: This number is above the range.");
        return -1;
    } 
    //this is where I would like to add the statement
    return 0;
}

NOTE: User jwdonahue pointed a better solution using fgets() / sscan() instead.注意:用户 jwdonahue 使用fgets() / sscan()指出了一个更好的解决方案


According to the manual page of scanf :根据scanf的手册页:

On success, these functions return the number of input items successfully matched and assigned ;成功时,这些函数返回成功匹配和分配的输入项的数量 this can be fewer than provided for, or even zero, in the event of an early matching failure.如果早期匹配失败,这可能会小于规定的值,甚至为零。

Since you have one value to read, you retrieve the return value of scanf() first and check it before checking number value:由于您要读取一个值,因此您首先检索scanf()的返回值并在检查number之前检查它:

int read_items;
read_items = scanf("%lld", &number);
if (read_items == 0) {
  printf("Not a number\n");
  return 1; // exit with an error status (!= 0)
}

Also you should check before that if even one value was read, which is described by the manual page:此外,您还应该在此之前检查是否读取了一个值,手册页对此进行了描述:

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.如果在第一次成功转换或匹配失败发生之前到达输入结尾,返回EOF EOF is also returned if a read error occurs如果发生读取错误,也会返回 EOF

Hence:因此:

int read_items;
read_items = scanf("%lld", &number);
if (read_items == EOF) {
  printf("No value entered or error occured\n");
  return 1; // exit with an error status (!= 0)
}
if (read_items == 0) {
  printf("Not a number\n");
  return 1; // exit with an error status (!= 0)
}

  
for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }

isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. isdigit(c)是 C 中的 function 可用于检查传递的字符是否为数字。 It returns a non-zero value if it's a digit else it returns 0如果是数字则返回非零值,否则returns 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM