c - 获取与预期不同的值在循环中运行。为什么?

标签 c loops scanf

因此,该程序在循环内接受三个值,一个 int、一个 float 和一个 char。 当它要求用户输入整数并且他们写.. 比方说,“House”程序陷入无限循环。

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

最佳答案

  • 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;
}

关于c - 获取与预期不同的值在循环中运行。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33855336/

相关文章:

c - Matlab - 从文件读取数据,同时忽略nan行

c - 当 scanf 输入是字符但转换说明符和变量是整数时,打印整数变量将返回 "weird"数字。为什么?

c - 将 scanf 与 3 个输入变量一起使用时出现段错误

python - 如何遍历数据点相互依赖的列表?

c# - 强制循环迭代

c - 字符串参数条件

c - prctl(PR_SET_PDEATHSIG) 竞争条件

c - 为什么这个递归搜索不进入第 2 层?

c - 执行后内存(泄漏)

php - WordPress 循环 : get current post count inside The Loop