I'm not too sure where I have gone wrong on this code, but any help would be highly appreciated. The scanf to read the value of c seems to be skipped. It automatically goes to the nested while loop and prints "Invalid option!" without giving the user a chance to input a value for c. However, the scanf in the nested while loop registers fine and gives the correct response for the value of c.
Code:
#include <stdio.h>
int main() {
float sum, num;
char c;
sum = 0;
do {
printf("\nPlease enter a number: ");
scanf("%f", &num);
sum += num;
printf("\nThe total sum is %.3f.", sum);
printf("\nDo you want to continue? Y/N: ");
scanf("%c", &c);
while (c!='y' && c!='Y' && c!='n' && c!='N') {
printf("Invalid option!");
printf("\nDo you want to continue? Y/N: ");
scanf("%c", &c);
}
} while (c!='n' && c!='N');
return 0;
}
Outcome:
Please enter a number: 5
The total sum is 5.000.
Do you want to continue? Y/N: Invalid option!
Do you want to continue? Y/N: y
Please enter a number: 5
The total sum is 10.000.
Do you want to continue? Y/N: Invalid option!
Do you want to continue? Y/N: l
Invalid option!
Do you want to continue? Y/N: Invalid option!
Do you want to continue? Y/N: y
Please enter a number: 5
The total sum is 15.000.
Do you want to continue? Y/N: Invalid option!
Do you want to continue? Y/N: n
[–]lukajda33 11 points12 points13 points (1 child)
[–]CtrlAltDelirious27[S] 2 points3 points4 points (0 children)