简体   繁体   English

输入,输出C程序

[英]Input, Output C Program

So thats my programm: This program scans and prints numbers, but I want it to print "Mistake" if a character is entered. 这就是我的程序:该程序扫描并打印数字,但是如果要输入字符,我希望它打印“ Mistake”。 It produces an infinite loop if I put something like an "a" in. Why? 如果我将类似“ a”的内容放入其中,则会产生无限循环。为什么?

#include <stdio.h> 

int main(void){
    printf("Enter a number: \n");
    int a;
    while(scanf("%d",&a)!=EOF){
        if(46<'a'<58){
        }
        else{
            printf("Mistake.");
            return -1;
        }
        printf("%d\n",a);
    }
}

First of all, you cannot chain the relational operators in C. You need to change 首先,您不能在C中链接关系运算符。您需要进行更改

 if(46<'a'<58){

to

if ((46 < 'a')  && ( 'a' < 58 )) {

to make it work. 使它工作。

That said, a char value is not a match for %d format specifier. 也就是说, char值与%d格式说明符不匹配。 You need to either 你需要

  • use %c to scan the input as char and check the ASCII value 使用%c将输入扫描为char并检查ASCII值
  • use %d to scan the int input and check for the return value of scanf() for success. 使用%d扫描int输入,并检查scanf()的返回值是否成功。 Also, in case scanf() fails for a non- int value, you need to clean up the input buffer before you loop again to avoid the infinite looping. 此外,如果scanf()失败,对于非int值,需要你再次循环之前清理输入缓冲器,以避免无限循环。

Read input as a string with fgets() , then test it as needed. 使用fgets()输入读取为字符串,然后根据需要对其进行测试。

Using scanf("%d", ...) returns 0, 1, or EOF when it fails, reads an int or end-of-file is detected. 如果使用scanf("%d", ...)失败,返回int或检测到文件结尾,则返回0、1或EOF Code could test that return value, but robust code simple does not use scanf() . 代码可以测试该返回值,但是简单的健壮代码不使用scanf()

char buf[100];
while(fgets(buf, sizeof buf, stdin) != NULL) {
  int a;
  if (sscanf(buf, "%d",&a) == 1) {
    printf("%d\n",a);
  } else {
    puts("Mistake.");
  }
}

if(46<'a'<58) does not work. if(46<'a'<58)不起作用。 it first compares 46<'a' which is 1 :true and then compares 1 < 58 which is also true. 它首先比较46<'a'1 :真,然后比较1 < 58也为真。 @124... @ 124 ...

46 < 'a' < 58 is always true, because 46 < 'a' evaluates to 1 , and then 1 < 58 evaluates to 1 . 46 < 'a' < 58始终为true,因为46 < 'a'计算结果为1 ,然后1 < 58计算结果为1 Also I suppose you want a , rather than 'a' , which is actually a literal. 另外,我想您需要的a而不是'a' ,它实际上是一个文字。 Additionally, I think your code has some logical problems. 另外,我认为您的代码有一些逻辑问题。

Here is the refined code: 这是精炼的代码:

#include <stdio.h> 

int main(void){
    puts("Enter a number:");
    char a;
    while(scanf("%c", &a) != EOF) {
        if(('0' <= a && a <= '9') || a == '\n'){
            putchar(a);
        }
        else
        {
            puts("Mistake.");
            return -1;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM