c - 仅通过 C 中的错误处理强制输入为正数

标签 c input user-input

我有一个小问题要问。我的程序应该只采用正整数。如果有非法内容,应提示用户重新输入数字。

我现在的代码是:

#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);
}

上面的代码几乎完成了我想要的;但是,当输入多个字母时,输出提示会打印多次,这让我很困扰。

   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: 

如果您能帮助我解决此问题或为这个看似微不足道的问题提供更好的解决方案,我将不胜感激。先谢谢了!

最佳答案

使用fgets将整行读入缓冲区。如果您只想处理第一个字符,则可以忽略其余字符。大致如下:

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

在浏览器中编码,可能包含错误痕迹。

关于c - 仅通过 C 中的错误处理强制输入为正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22383449/

相关文章:

c - 服务放入安装功能后无法启动

c - 从 shell 脚本向 C 程序发送输入

java - 如何将用户输入添加到java中的并行数组?

比较字符串与十六进制字符串

c - 将任意结构指针数组传递给 C 函数?

javascript - HTML::添加输入标签的链接

javascript - 输入类型 number + ng-keypress 以允许 '-' 符号

javascript - 如何在 Javascript 中获取当前格式化日期 dd/mm/yyyy 并将其附加到输入

ruby - 如何通过 Rack 中间件处理用户输入的无效字节序列?

dom - 获取用户输入的字符