本文介绍了如何阻止用户在 C 中输入字符作为 int 输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码的一部分:

Heres a part of my code:

    printf("\nEnter amount of adult tickets:");
    scanf("%d", &TktAdult);
    while (TktAdult<0){
        printf("\nPlease enter a positive number!");
        printf("\nEnter amount of adult tickets:");
        scanf("%d", &TktAdult);
    }

现在它只能阻止用户输入负值,但我如何添加它以便它也阻止用户输入字符??

Right now it can only stop user from entering a negative value, but how do I add to it so it also stops user from entering a char??

推荐答案

以下代码拒绝用户输入:

The following code rejects user input that are:

  • 由//1 处理的非数字;

  • non-numeric as handled by // 1;

负数由//2 处理;

正数后跟由//3 处理的非数字字符

positive numbers followed by non-numeric chars as handled by //3

 while (1) {
     printf("\nEnter amount of adult tickets: ");
     if (scanf("%d", &TktAdult) < 0 ||  // 1
             TktAdult < 0 ||  // 2
             ((next = getchar()) != EOF && next != '\n')) {  // 3
         clearerr(stdin);
         do
             next = getchar();
         while (next != EOF && next != '\n');  // 4
         clearerr(stdin);
         printf("\nPlease enter a positive number!");
     } else {
         break;
     }
 }

此外,//4 清除标准输入的缓冲非数字字符//3(即 123sda - scanf 需要 123 但在缓冲区中留下 'sda').

Also, // 4 clears the standard input of buffered non-numeric characters following case // 3 (i.e. 123sda - scanf takes 123 but leaves 'sda' in the buffer).

这篇关于如何阻止用户在 C 中输入字符作为 int 输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:41