【问题标题】:Getting a different value than expected runs in a loop. Why?获得与预期不同的值在循环中运行。为什么?
【发布时间】:2015-11-22 13:34:38
【问题描述】:

所以,这个程序在循环中接受三个值,一个 int、一个 float 和一个 char。 当它要求用户输入整数并且他们写..比方说,“房子”程序陷入了无限循环。

    #include <stdio.h>

int main(void){

    int i;
    float f;
    char c;

    while(i!=99){

        printf("Enter an int, a float and a char separated by commas: ");
        int count = scanf("%d,%f,%c",&i,&f,&c);
        printf("Int is: %d, Float is: %1.f, Char is: %c",i,f,c);

        if (count != 2){
            fflush(stdin);
            printf("\nerror\n");
        }

    }

    return 0;
}

【问题讨论】:

  • i 在循环条件while(i!=99) 中使用之前未初始化。
  • 不仅i可以未初始化使用,所有变量(count除外)都可以使用。这是因为scanf 第一次调用可能会失败。

标签: c loops scanf


【解决方案1】:
  • scanf() 留下不被解释为数据读取的字符,所以在下一次迭代中,scanf() 尝试再次读取字符并再次失败,然后将导致无限循环。
  • fflush(stdin); 是未定义的行为,请勿使用它。
  • i!=99中使用了未初始化的i,这也是未定义的行为。

试试这个:

#include <stdio.h>

int main(void){

    int i=0;
    float f=0.0f;
    char c=' ';

    while(i!=99){

        printf("Enter an int, a float and a char separated by commas: ");
        int count = scanf("%d,%f,%c",&i,&f,&c);
        printf("Int is: %d, Float is: %1.f, Char is: %c",i,f,c);

        if (count != 3){ /* adjusted to match the scanf */
            int dummy;
            while((dummy=getchar())!='\n' && dummy!=EOF); /* skip one line */
            printf("\nerror\n");
            if (dummy == EOF) break; /* there won't be any more input... */
        }

    }

    return 0;
}

【讨论】:

    【解决方案2】:

    在这-

    if (count != 2){
            fflush(stdin);                  // undefined behaviour
            printf("\nerror\n");
        }
    

    还应针对3 而不是2 测试countscanf 如果成功,将返回3)。而不是 fflush(stdin) ,使用它来清除输入流-

    int c;
    if (count != 3){
       while((c=getchar())!='\n' && c!= EOF);
      printf("\nerror\n");
    }
    

    你还有 i 未初始化。所以,要么初始化它,要么不使用while循环使用do-while -

    do{
       //your code
      }while(i!=99);
    

    【讨论】:

    • @hydrz 我不确定你在说哪个循环?
    • 哦,成功了!是的,我忘记了几件事,因为我编写此代码只是为了在这里询问它。顺便说一句,你能解释一下那条线吗? “while((c=getchar())!='\n' && c!= EOF);”我是说。
    • @hydrz 内部while 循环将从stdin 读取并存储在c 中,直到遇到新行或EOF。这样stdin 将被清除,并且在下一次迭代中scanf 不会失败。
    • 我明白了...谢谢你的帮助!
    猜你喜欢
    • 2015-02-11
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多