The reason it hangs, or seems to hang, is because your in a loop. The
scanf() is waiting for an input. When you type in an alpha character, the
return value isn't 1, so you exit the loop. You might be better off using a
"yes" or "no" style system to exit the loop. In essence, something like:
char ch = 'Y'; // Initialise to enter loop
while( (ch == 'Y') || (ch == 'y') ) {
scanf();
// Rest of code
printf("Continue ?");
ch = getchar();
}
Best of luck
Vas
----- Original Message -----
From: "Mary Sipple" <ms...@in...>
To: <dev...@li...>
Sent: Thursday, July 12, 2001 4:47 AM
Subject: [Dev-C++] Basic C question: scanf
> I've written a short program using Dev-C++ 4, but it does not execute as I
> would expect. The code is as follows:
>
> #include <stdio.h>
>
> int main(int argc, char *argv[])
> {
> double salary, fed_withhold, state_withhold;
> double salary_sum = 0, fed_sum = 0, state_sum = 0;
>
> printf("Enter salaries: ");
> while (scanf("%lf", &salary) == 1){
> fed_withhold = salary * .17;
> state_withhold = salary * .03;
> printf("salary: %.2f fed tax: %.2f state tax: %.2f\n",
> salary, fed_withhold, state_withhold);
> salary_sum += salary;
> fed_sum += fed_withhold;
> state_sum += state_withhold;
> }
> printf("\nSalary total: %.2f Fed tax total: %.2f State tax total:
%.2f\n",
> salary_sum, fed_sum, state_sum);
>
> system("PAUSE");
> return 0;
> }
>
> When the program is run, the prompt "Enter salaries:" is printed. After
> that, I enter a series of numbers, then press the Enter key. The printf in
> the loop is executed for each number input, but then the program hangs. I
> have to either interrupt the program (<cntrl>-z worked for this) or type
in
> alpha characters and hit Enter. At that point the printf after the while
> loop is executed.
>
> What have I got wrong or what is it that I don't understand?
>
> Thanks,
>
> Mary
>
>
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> http://lists.sourceforge.net/lists/listinfo/dev-cpp-users
|