简体   繁体   English

C 基础知识,如果输入不是正的 integer,要求新的输入

[英]C basics, if the input is not a positive integer, ask for a new input

i am trying to make this basic program: -It asks for an input我正在尝试制作这个基本程序: - 它要求输入

A: if it is a positive integer, thats good, and i can use that on the second part of the program. A: 如果是正的 integer,那很好,我可以在程序的第二部分使用它。

B: if the input is not a positive integer, it will ask for a new input until it gets a positive integer. B:如果输入不是正 integer,它将要求一个新的输入,直到它得到一个正 integer。

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

    int main()
    {
        int number;
    
        printf("Please enter a positive integer:\n");
    
        do {
                scanf("%d", &number);
    
        }
    
    
        while (number >= 0);
    
    
        return 0;
    }

You have the loop condition backwards - you're supposed to continue looping as long as the input is not a positive integer:你有循环条件 - 只要输入不是正数 integer,你就应该继续循环:

do {
    scanf("%d", &number);
}
while (number <= 0);

First read full lines , as invalid input (like eg letters) will not be removed from the input buffer.首先读取整行,因为无效输入(例如字母)不会从输入缓冲区中删除。 Then parse the input using sscanf .然后使用sscanf解析输入。 Then use the %u format to parse unsigned int values Lastly always check what sscanf returns .然后使用%u格式解析unsigned int值最后总是检查sscanf返回什么

Also remember to add a check for zero.还记得添加一个零检查。 And if the user wanted to break out of the input loop, possibly exiting the program.如果用户想跳出输入循环,可能会退出程序。

Putting it together it could be something like this:放在一起可能是这样的:

unsigned number;
char number_buffer[32];

printf("Please enter a positive integer:\n");
while fgets(number_buffer, sizeof number_buffer, stdin) != NULL)
{
    if (sscanf(number_buffer, "%u", &number) == 1 && number > 0)
    {
        // Successfully read non-negative and non-zero number, end loop
        break;
    }

    // Invalid input, ask the user again
    printf("Invalid input. Please enter a positive integer (not negative, not zero):\n");
}

if (feof(stdin) || ferror(stdin))
{
    // The user pressed the EOF keyboard-sequence, or there was an error reading
    // TODO: Handle these cases appropriately
}

I recommend you put all of this in a separate function.我建议您将所有这些放在单独的 function 中。

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

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