2010-11-13 96 views
1

我正在使用这段代码来读取用户输入并检查它是否是数字,但是它真的只适用于数字和字母。我希望它能与每个字符一起工作。例如 ”!?%”。我已经试图通过“isascii”来改变“isalnum”,但这不起作用。用于检查用户输入的do-while循环使用c

#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; 
    } 
+2

莫非你请修理你的缩进? – 2010-11-13 11:59:08

+0

我不明白你的问题。你想测试什么字符*拒绝*? – 2010-11-13 12:00:54

+0

我想拒绝除数字以外的所有字符。 – Ordo 2010-11-13 12:06:41

回答

2

除非你有特殊要求,应在严格C89使用fgetssscanf

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"); 
} 
2

以正确的方式与清除输入缓冲区,检查溢出的样子:

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

int readLong(long *l) 
{ 
    char *e,in[20]; 
    fgets(in,20,stdin); 
    if(!strchr(in,'\n')) while(getchar()!='\n'); 
    else *strchr(in,'\n')=0; 
    errno=0; 
    *l=strtol(in,&e,10); 
    return *in&&!*e&&!errno; 
} 

int main() 
{ 
    long l; 
    if(readLong(&l)) 
    printf("long-input was OK, long = %ld",l); 
    else 
    puts("error on long-input"); 
    return 0; 
} 
+0

+1,但你应该增加'in'的大小。 “long”可能是64位,-9223372036854775808(包括' - '的20个字符)是有效的,但不能被您的函数接受。 – pmg 2010-11-13 13:49:28

+0

对不起,但我太复杂了。我只想要一个简单的解决方案。有什么我可以使用,而不是isalnum(),我试过isascii(),但这不适合我。 – Ordo 2010-11-14 20:24:26

+0

它太难以调用函数了吗?每次你自己处理inputbuffer都不难? – user411313 2010-11-14 21:17:24