loop is asking me twice instead of once

Hi,

the below code should, if I press 1, ask me to continue, but it prints out

Would you like to continue (y/n)Would you like to continue (y/n)
instead of just once like this
Would you like to continue (y/n)

However, if I call the function outside of case switch then it asks properly.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void test();
void choose();
int main(void)
{	
//if i call here before choose() it works properly
	//test();
	choose();
	return 0; 
}

void choose()
{
	int choice;
		
	do
	{
		printf("1 - Testing if double ask\n");
		printf("2 - Exit\n");
		printf("Please enter your choice: ");		
		scanf("%i", &choice);
	
		switch(choice)
		{

			case 1:			
				test();
				break;
			default:
				if(choice !=2)
					printf("Input Not Recognized!\n");
				break;			
		}
	}
	while(choice !=2);
	if(choice == 2)
		printf("Ciao!");
}
void test()
{
		char *name = malloc (256);

		do		
		{
			printf("Would you like to continue (y/n)\n");
			fgets(name, 256, stdin);
		}
		while(strncmp(name, "n", 1) != 0);
		free (name);
}
Last edited on
If I had to guess I'd say scanf() is leaving the \n from when you pressed enter after the 1 in the buffer, so the first time you try to later call fgets(), it hits that newline and reads that as an empty string.
YES i've figured it out, it sure is scanf the culprit, something about newline or something, and adding this:

getchar(); after scanf of choice outputs once!
Topic archived. No new replies allowed.