力输入是正数仅在C处理错误 [英] Force input to be positive numbers only with error handling in C

查看:126
本文介绍了力输入是正数仅在C处理错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题要问。我的程序应该只需要阳性整数。如果有什么非法的,用户应再次多项提示输入。

I have a trivial question to ask. My program should take postive integers only. If there is anything illegal, the user should be prompted to input a number again.

在code我现在是:

#include<stdio.h>
int main(){
int reads;
int num=0;
char a;

while(num<=0){
  printf("Please Enter positive integer: ");
  while(((reads = scanf("%d%c", &num, &a)) != 2 && reads != EOF) || a != '\n' ){
    do {
     printf("Please Enter positive integer: ");
     reads = scanf("%c", &a);
    }while(reads != EOF && a != '\n');
  }
}
printf("Num is: %d", num);
}

在code上面几乎没有我想要的东西;然而,当输入多个字母,则输出提示将打印多次,这困扰了我很多。

The code above almost did what I want; however, when the input is multiple letters, the output prompts will be print multiple times, which bothers me a lot.

   Please Enter positive integer: pdesf
    Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: dfwerasdfwe
    Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: 

我倒是AP preciate如果你能帮助我解决这个问题或这个相宜琐碎的问题提供更好的解决方案。提前感谢!

I'd appreciate if you can help me fix this or offer better solutions for this seemly trivial problem. Thanks ahead!

推荐答案

使用与fgets 来阅读一整行到缓冲区中。如果你只是要处理的第一个字符,你可以忽略其他。沿着线的东西:

Use fgets to read a whole line into a buffer. If you only want to process the first character, you can just ignore the rest. Something along the lines of:

char buf[MAX_LINE_LEN];
if (fgets(buf, MAX_LINE_LEN, stdin))
{
    char a = buf[0];
    /* Do handling... */
}
else
{
    /* error */
}

在浏览器中codeD,可能包含错误的痕迹。

这篇关于力输入是正数仅在C处理错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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