Reputation: 13
what is the problem here? scanf doesnt seems to working in while loop. i was trying to find out vowel & consonent until user wants.
Here's the code:
#include <stdio.h>
main()
{
char x,c;
do
{
printf("enter\n");
scanf("%c",&x);
if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
printf("vowel\n");
else
printf("consonent\n");
printf("do u want to continue ?(y/n)\n");
scanf("%d",&c);
if(c=='n')
printf("thnks\n");
} while(c=='y');
return 0;
}
Upvotes: 1
Views: 1023
Reputation: 5980
Please try with this code to run the loop multiple times.
EDIT: Different solution without fflush(stdin)
. Please define a string of 8 characters as
char str[8];
and modify the code in the loop as
fgets(str, 8, stdin); // To read the newline character
printf("do u want to continue ?(y/n)\n");
scanf("%c",&c);
fgets(str, 8, stdin); // To read the newline character
Upvotes: -1
Reputation: 47428
Both scanfs should be changed like this:
scanf(" %c",&x);
...
scanf(" %c",&c);
Note the space before the %
, it's important: it consumes leading whitespace, which includes the endline characters left over in stdin
after processing the input.
Upvotes: 0
Reputation: 406
Here is the Correct code:
#include <stdio.h>
int main()
{
char x,c;
do
{
printf("enter\n");
scanf("%c",&x);
getchar(); //to remove the \n from the buffer
if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
printf("vowel\n");
else
printf("consonent\n");
printf("do u want to continue ?(y/n)\n");
scanf("%c",&c); //Here you were using %d instead of %c
getchar(); //to remove the \n from the buffer
if(c=='n')
printf("thnks\n");
}while(c=='y');
return 0;
}
Upvotes: 1
Reputation: 4775
Change code to scanf("%c",&c)
your original code is getting the y/n entries as digits not characters
Edit:
Probably you are getting the carage return instead of the character try using getc
or fgets
instead and get the first character.
Upvotes: 2
Reputation: 108
I think the problem might be here: scanf("%d",&c); It should be:
scanf("%c",&c);
Upvotes: 1
Reputation: 70929
You are trying to read a character using %d
which is wrong. Use %c
instead.
Upvotes: 6