EDIT: I had to add a getchar(); after scanf("%i", &choice); now it asks only once!
Apparently its the case switch that's causing it to output twice. If I call the function outside the case switch it ouputs 1, but if I called it inside the switch it outputs twice
What is causing this? I suspect the scanf choice?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void test();
void choose();
int main(void)
{
//if i call here its fine
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)
{//but pressing 1 here asks twice?
case 1:
test();
break;
default:
if(choice !=2)
printf("Input Not Recognized!\n");
break;
}
}
while(choice !=2);
if(choice == 2)
printf("Ciao!");
}
void test()
{
printf("HELLO");
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);
}
First: you can't compare C strings with the comparison operators !=
and ==
. You'll need to use strcmp
for this.
Furthermore I think you'll find a do { ... } while
loop more useful in this case. You're checking name
once before the user has had a chance to add any input.
The next thing to be aware of is that fgets
will retain the newline in your input, so you'll need to address this in your usage of strcmp
.