为什么当我在C程序中的while循环中有2个scanf语句时,在1个循环之后只有其中一个会运行?

问题描述 投票:0回答:1
#include "stdafx.h"
#include <stdio.h>
#include <Windows.h>

double FindPopulation(char);

void main()
{
    char state;
    double population;
    int flag = 1;

    while(flag == 1) 
{

    printf("This program will display the population for any New England state. \n");

    printf("e=ME, v=VT, n=NH, m=MA, c=CT, r=RI\n");

    printf("Enter the state using the above symbols: ");

    scanf("%c", &state);

    printf("You entered %c \n", state);

    population = FindPopulation(state);

    if (population == 0)
    {
        printf("You have entered a invalid state!\n");
    }

    else

        printf("This state has a population of %.2f million!!\n", population);

    printf("To quit please enter the number 0, to run this program again please enter the number 1: ");

    scanf("%d", &flag);

    }

}

double FindPopulation(char s) 
{

    double pop;

    switch (s)
    {
    case 'e': pop = 1.34;
        break;

    case 'v': pop = 0.63;
        break;

    case 'n': pop = 1.36;
        break;

    case 'm': pop = 6.90;
        break;

    case 'c': pop = 3.57;
        break;

    case 'r': pop = 1.06;
        break;

    default: pop = 0;
    }

    return pop;

}

我是C的新手,之前从未在C中循环过。无论如何,这个想法是,有2个scanfs,其中一个要求用户输入以恢复正确的状态填充,另一个scanf将是一个打破while循环的标志。标志scanf工作得非常好。如果我键入0,它将跳出循环并结束程序。如果我键入1,它将继续循环。但是,第一个循环后的第一个scanf将停止工作。它不会要求另一个用户输入。相反,它将跳过自己并打印输出:

"Enter the state using the above symbols: You entered "

对于第二次扫描,即使多次迭代,我也可以按0退出任何时间。

有人能告诉我为什么一个scanf正常工作而另一个失败?

c while-loop scanf
1个回答
1
投票

当你第一次使用state获得变量scanf的字符输入时,它会将它存储到state。然后你使用scanf获得标志输入。如果按0和Enter键,则0(int)存储在flag中,而\n保留在文件stdin中。

下一个scanf从stdin(标准输入文件)获取字符(%c),因为\n是stdin中的第一个字符,所以它将\n放在state中。由于您的函数FindPopulation()不将\n作为有效输入,因此会显示错误。

您可以通过在getchar();之后放入scanf("%d", &flag);来解决它。 getchar();从stdin获取一个角色,即从stdin中移除\n。 您还可以使用while((c = getchar()) != '\n' && c != EOF);删除stdin中的所有字符。

© www.soinside.com 2019 - 2024. All rights reserved.