Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <stdio.h>

void main()
{
	int num, sum = 0;
	char answer;

	while (1)
	{
		printf_s("add another number ? ");
                //here need to clean the buffeer	
              	scanf_s("%c", &answer);

		if (answer == 'n' || answer == 'N')
			break;
		printf_s("enter the number : ");
		scanf_s("%d", &num);
		sum += num;
	}
	printf_s("Total sum is %d\n", sum);
}


What I have tried:

hey i need to clean the buffer for asking every time the question "add another number? "
and wait to answer.
now the program get the first "y" (yes) and not wait for answer to this question again.
please help
Posted
Updated 4-Apr-18 22:42pm
v2

The answer is: no, you dont need to clear the variable because the new input is writing it.

But if you want you can do it.
C++
while (1)
{
  printf_s("add another number ? ");
  answer = 0;//clear buffer 
  scanf_s("%c", &answer,1);//added size of the buffer
  //better exit check
  if( (answer != 'y') && (answer =! 'Y') )
	break;
 
Share this answer
 
With scanf, the %d format will consume leading white spaces which might be in the input buffer (e.g. the new line not read at the end of a previous input) while the %c format will not do so. But you can make it doing so by inserting a space in front of the format:
C
scanf_s(" %c", &answer);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900