problem in char variable
I am making a simple to calculate the digits of a number. The basic code is fine and it is working.
Now I want that if the user is interested he can input another no and found the sum of digit for it.
For this I am using a while loop with condition that a char variable x has the value 'y'. At the end of the loop I ask the user to press 'y' if he is interested in running the program again.
But the while loop does not run again. Here is the code
The problem is that the control moves out of the outer while loop even if the user types 'y'.
int num, n, rem, sum = 0;
char x = 'y';
while(x == 'y')
printf("enter a number less than equal to 32767\n");
n = num;
rem = n%10;
n = n/10;
sum = sum + rem;
printf("the sum of digits is %d", sum);
printf("\n do you want to continue,press 'y' if yes, else press any other
Thanks a lot friends
When you enter your number, the buffer has the number and the newline from the enter. scanf() takes the number but leaves the newline on the buffer. The next scanf() then take the newline, so the value of x becomes that of the newline. A newline is not 'y', so the loop ends. A possible solution is to place a getchar() after the first scanf(). You might want to read the FAQ on How do I get my program to wait for a keypress?
or you can always red the whole line with the fgets (that will not leave a new char in the input stream
and when extract the user input from the buffer using sscanf