使用 c 检查用户输入的 do-while 循环 [英] do-while loop for checking users input using c

查看:28
本文介绍了使用 c 检查用户输入的 do-while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这段代码来读取用户输入并检查它是否是数字.但真诚地它只适用于数字和字母.我希望它适用于每个字符.例如 "!?%".我已经尝试通过isascii"更改isalnum",但这不起作用.

I'm using this piece of code to read users input and check if it is a number or not.But sincerly it just works for numbers and letters. I want it to work with every char. For example "!?%". I have already tried to change the "isalnum" by "isascii" but that does not work.

#include <stdio.h>
#include <ctype.h>

int main ()
  {

    int a;
    int b = 1;
    char c ;

     do
     { 
       printf("Please type in a number: ");

       if (scanf("%d", &a) == 0)
       {
         printf("Your input is not correct\n");
         do 
         {
           c = getchar();
         }
         while (isalnum(c));  
         ungetc(c, stdin);    
       }
       else
       { 
         printf("Thank you! ");
         b--;
       }

     }
     while(b != 0); 

     getchar();
     getchar();

     return 0;
  }

推荐答案

除非你有特定要求,否则应该使用 fgetssscanf

Unless you have specific requirements, you should use fgets and sscanf

while (1) {
    char buf[1000];
    printf("Please input a number: ");
    fflush(stdout);
    if (!fgets(buf, sizeof buf, stdin)) assert(0 && "error in fgets. shouldn't have hapenned ..."):
    /* if enter pending, remove all pending input characters */
    if (buf[strlen(buf) - 1] != '\n') {
        char tmpbuf[1000];
        do {
            if (!fgets(tmpbuf, sizeof tmpbuf, stdin)) assert(0 && "error in fgets. shouldn't have hapenned ...");
        } while (buf[strlen(tmpbuf) - 1] != '\n');
    }
    if (sscanf(buf, "%d", &a) == 1) break; /* for sufficiently limited definition of  "numbers" */
    printf("That was not a number. Try again\n");
}

这篇关于使用 c 检查用户输入的 do-while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆