#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;
}
I am new to C, never did while loops in C before. Anyways the idea is, there are 2 scanfs, one of them asks for user input to bring back the correct state population, the other scanf will be a flag that breaks out the while loop. The flag scanf works perfectly fine. If I type in a 0 it will break out of the loop and end the program. If I type in a 1 it will continue to loop. However, the first scanf after the first loop will stop working. It will not ask for another user input. Instead it will skip itself and print the output:
"Enter the state using the above symbols: You entered "
For the second scanf I can press 0 to quit any time even after multiple iterations.
Can someone tell me why is one scanf is working correctly while the other one fails?