在C编程中使用isdigit

时间:2017-03-01 22:58:09

标签: c windows

我需要一些关于如何在此示例中使用isdigit()的帮助:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
   int usr_option;
   do
   {
      printf("\t\t\t************************MENU***********************\n");
      printf("\t\t\t***  1. Enter Code\t\t\t\t***\n");
      printf("\t\t\t***  2. Encrypt code and verify if correct\t***\n");
      printf("\t\t\t***  3. Decrypt code\t\t\t\t***\n");
      printf("\t\t\t***  4. Display number of times code was enter\t***\n");
      printf("\t\t\t***\t\t(i) Successfully\t\t***\n");
      printf("\t\t\t***\t\t(i) Unsuccessfully\t\t***\n");
      printf("\t\t\t***  5. Exit Program\t\t\t\t***\n");
      printf("\t\t\t***************************************************\n");
      printf("\nPlease enter your option from the menu: ");
      scanf("%d", &usr_option); 
      if (isdigit(usr_option))
      {
          //Inside here is my switch case e.g switch(usr_option){/*code*/}
      }
      else
      {
        printf("Need to enter a digit\n");
      }          
    }//end do while 
    while(usr_option != 5);
    return 0;
 }

如何实现此代码以避免进入无限循环? 我尝试过不同的方式,但似乎并不想工作。我使用编译器CodeBlocks和Sublime Text 3。

1 个答案:

答案 0 :(得分:0)

如果您通过scanf("%d", &usr_option);阅读了某个号码,则无需使用is_digit()您可以使用ifswitch,例如

switch(usr_option)
{
    case 1: enter_code(); break;
    case 2: encrypt(); break;

如果要检查字符串中的字符是否为数字,则只需要is_digit

即。 '1' != 1