Reputation: 121
When I execute the following program it get the user input for account details and then prints it correctly, but it cannot read the opt value (y/n). It automatically calls again. How can I get the program to exit when the user inputs "n"?
char opt;
do
{
//Getting user input
printf("\n Enter the Account Number:\n ");
scanf("%d",&gAccNo_i);
printf("\n Enter the Account Holder's Name:\n ");
scanf("%s",gCustName_c);
printf("\n Enter the Balance Amount:\n ");
scanf("%f",&gBlncAmt_f);
//Printing the input data.
printf("\n Account Number : %d",gAccNo_i);
printf("\n Customer Name : %s",gCustName_c);
printf("\n Balance Amount : %f",gBlncAmt_f);
printf("\n Do u want to wish to continue?(y/n)");
scanf("%c",&opt);
}while(opt!='n');
Upvotes: 1
Views: 263
Reputation: 15354
use opt=getch();
inplace of scanf("%c",&opt);
OR
scanf
reads the whitespace that is left in the buffer by previous line. To skip whitespace, add a space to the "%c":
scanf(" %c", &opt);
Upvotes: 3
Reputation: 22114
scanf("%c",&opt);
Will actually read in a space/newline character. Which obviously will not be equal to 'n'.
You may like to take the input as a string and then verify if the first character is a 'n'.
char opts[5];
scanf("%s",opts);
while(opts[0] !='n');
Upvotes: 0