c - 循环在第一次后跳过 scanf 语句

标签 c loops for-loop scanf

这是 main() 的代码:

int main (void)
{
float acres[20];
float bushels[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
char choice;
int counter = 0;

for(counter = 0; counter < 20; counter++)
{   
    printf("would you like to enter another farm? "); 

    scanf("%c", &choice);

    if (choice == 'n')
    {
        printf("in break ");
        break;
    }

    printf("enter the number of acres: ");
    scanf("%f", &acres[counter]);

    printf("enter the number of bushels: ");
    scanf("%f", &bushels[counter]);

}


return 0;
}

每次程序运行时,第一次 scanf 工作正常,但在第二次通过循环时,输入字符的 scanf 不运行。

最佳答案

scanf中的%c前加一个空格。这将允许 scanf 在读取 choice 之前跳过任意数量的空格。

scanf("%c", &choice); 是唯一需要的更改。

scanf("%c", &choice); 之前添加一个 fflush(stdin); 也可以。 fflush 调用将刷新输入缓冲区的内容,然后再通过 scanf 读取下一个输入。

scanf("%c", &choice); 的情况下,即使输入读取缓冲区中只有一个字符,scanf 也会将此字符解释为有效的用户输入并继续执行。 scanf 的不正确使用可能会导致一系列奇怪的错误[比如在 while 循环中使用时的无限循环]。

关于c - 循环在第一次后跳过 scanf 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14639166/

相关文章:

c++ - 位补函数在 C++ 的 For 循环中做什么?

c - 如何编译使用 getsubopt() 的代码?

c++ - (1<<32) 和 (1<<i) 之间的差异,其中 i == 32

c - 如果用户输入大于 10 的数字,为什么程序会循环相同的输出?

c - 用于获取 int 的 K&R 代码

javascript - Array.prototype.splice() 在迭代时不删除对象

C编程元素数组到sprintf()

java - Hadoop循环 reducer

javascript - for循环中的闭包

javascript - 为以编程方式创建的 div 创建点击事件