scanf and printf just skips after 1st time - c

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;
}

You are trying to read a character using %d which is wrong. Use %c instead.

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.

I think the problem might be here:
scanf("%d",&c);
It should be:
scanf("%c",&c);

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;
}

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.

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

Related

getchar() not working in c

getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working.
I am not able to figure out the root cause of the issue, can anyone please help me.
#include<stdio.h>
int main()
{
int x, n=0, p=0,z=0,i=0;
char ch;
do
{
printf("\nEnter a number : ");
scanf("%d",&x);
if (x<0)
n++;
else if (x>0)
p++;
else
z++;
printf("\nAny more number want to enter : Y , N ? ");
ch = getchar();
i++;
}while(ch=='y'||ch=='Y');
printf("\nTotal numbers entered : %d\n",i);
printf("Total Negative Number : %d\n",n);
printf("Total Positive number : %d\n",p);
printf("Total Zero : %d\n",z);
return 0 ;
}
The code has been copied from the book of "Yashvant Kanetkar"
I think, in your code, the problem is with the leftover \n from
scanf("%d",&x);
You can change that scanning statement to
scanf("%d%*c",&x);
to eat up the newline. Then the next getchar() will wait for the user input, as expected.
That said, the return type of getchar() is int. You can check the man page for details. So, the returned value may not fit into a char always. Suggest changing ch to int from char.
Finally, the recommended signature of main() is int main(void).
That's because scanf() left the trailing newline in input.
I suggest replacing this:
ch = getchar();
With:
scanf(" %c", &ch);
Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than consuming a single char in the previous scanf() because it ignores any number of blanks.
When the user inputs x and presses enter,the new line character is left in the input stream after scanf() operation.Then when try you to read a char using getchar() it reads the same new line character.In short ch gets the value of newline character.You can use a loop to ignore newline character.
ch=getchar();
while(ch=='\n')
ch=getchar();
When you using scanf getchar etc. everything you entered stored as a string (char sequence) in stdin (standard input), then the program uses what is needed and leaves the remains in stdin.
For example: 456 is {'4','5','6','\0'}, 4tf is {'4','t','f','\0'} with scanf("%d",&x); you ask the program to read an integer in the first case will read 456 and leave {'\0'} in stdin and in the second will read 4 and leave {''t','f',\0'}.
After the scanf you should use the fflush(stdin) in order to clear the input stream.
Replacing ch = getchar(); with scanf(" %c", &ch); worked just fine for me!
But using fflush(stdin) after scanf didn't work.
My suggestion for you is to define a Macro like:
#define __GETCHAR__ if (getchar()=='\n') getchar();
Then you can use it like:
printf("\nAny more number want to enter : Y , N ? ");
__GETCHAR__;
I agree that it is not the best option, but it is a little bit more elegant.
Add one more line ch = getchar();
between scanf("%d",&x); and ch = getchar();
then your code work correctly.
Because when you take input from user, in this time you press a new line \n after the integer value then the variable ch store this new line by this line of code ch = getchar(); and that's why you program crash because condition can not work correctly.
Because we know that a new line \n is also a char that's why you code crash.
So, for skip this new line \n add one more time ch = getchar();
like,
ch = getchar(); // this line of code skip your new line when you press enter key after taking input.
ch = getchar(); // this line store your char input
or
scanf("%d",&x);
ch = getchar(); // this line of code skip your new line when you press enter key after taking input.
pieces of code work correctly.

My c program is not giving proper result

The following code is not working properly.
scanf and printf statements in the ques2() function are not working in execution. please help me with it.
void main()
{
printf("\t\t\t\t\tKBC");
ques1();
}
void ques1()
{
char c;
printf("\nQ1 WHAT IS THE CAPITAL OF INDIA?");
printf("\na. Delhi \tb. Kolkata");
printf("\nc. Rome \td. China\n");
scanf("%c",&c);
if(c=='a')
{
ques2();
}
else printf("wrong answer");
}
ques2()
{
printf("ques2");
char d;
scanf("%c",&d);
printf("%c",d);
ques3();
}
ques3()
{
printf("ques3");
char d;
scanf("%c",&d);
printf("%c",d);
}
When you use:
scanf("%c",&c);
the newline character is still left in the input stream after the character is read. Next time such a statement is used, the newline character is read into c. If you want to skip leading whitespaces, replace the format in those to " %c".
scanf(" %c",&c);
Make that change in ques1, ques2, and ques3.
Update, in response to OP's comment
When you use
scanf("%c",&c);
If your type a followed by Enter, then the first scanf stores 'a' in c. The second scanf stores a '\n' in c.
When you use
scanf(" %c",&c);
all leading whitespace characters are skipped. Hence, the '\n' from the input stream is not read into c.
I got another answer to the question. There is another method of clearing memory of the buffer i.e fflush(stdin) before scanf statement
this function clears anything that is in the buffer and then allow us to use scanf simply.

why printf() plays twice?

I wrote this program:
#include <conio.h>
#include <stdio.h>
void main()
{
char ch='a';
while(ch!='y'&&ch!='n')
{
printf("\nDo you want to print the output?(y/n)");
scanf("%c",&ch);
}
if(ch=='y')
printf("\n accepted!");
getch();
}
expected output:
Do you want to print the output?(y/n)1
Do you want to print the output?(y/n)5
Do you want to print the output?(y/n)y
accepted!
Instead I get:
Do you want to print the output?(y/n)
Do you want to print the output?(y/n)1
Do you want to print the output?(y/n)
Do you want to print the output?(y/n)5
Do you want to print the output?(y/n)
Do you want to print the output?(y/n)y
accepted!
I don't know that why the sentence"Do you want to print the output?(y/n)" is written twice in output?
Beacuse scanf accepts a \n character and leaves it in the buffer.
To consume that character you can use:
scanf(" %c",&ch);
This should work for you:
(You have to remove all '\n' and put a space before %c)
(Because scanf read's everything to \n and the new line is still in the buffer, so in the next iteration the new line get's read from scanf)
#include <conio.h>
#include <stdio.h>
void main()
{
char ch='a';
while(ch!='y'&&ch!='n')
{
printf("Do you want to print the output?(y/n)");
scanf(" %c",&ch);
}
if(ch=='y')
printf("accepted!");
getch();
}
So you get your output:
Do you want to print the output?(y/n)1
Do you want to print the output?(y/n)5
Do you want to print the output?(y/n)y
accepted!
Make the scanf in your function like this.
scanf(" %c",&ch);
Reason for making like this. When you are giving an input to that question that time enter will be pressed. So here when the enter is pressed newline character is placed. So scanf get the newline as a character then the loop will continue for the next time. If you give the spaces before the control string it will skip the white line characters from our input, then it ask the input for that.
Problem with the input buffer. However, the solution is very simple:
instead of scanf(" %c",&ch);, use:
do { ch=getchar(); } while(ch=='\n');

Simple C code not working

I have written a simple code to check whether a given character is present in the string entered by the user but it doesn't seem to work.
#include<stdio.h>
#include<string.h>
int main()
{
char a[20],b;
int i,p=0,n;
printf("Enter the string-");
scanf("%s",a);
printf("\nEnter the character-");
scanf("%c",&b);
n=strlen(a);
for(i=0;i<n;i++)
{
if(a[i]==b)
{
printf("\ncharacter is present in string\n");
p=1;
break;
}
}
if(p==0)
printf("\nchracter is not present in string\n");
return 0;
}
The output I get is this: http://i58.tinypic.com/2gvnedt.png
I do not see what is wrong with the code. If I replace "scanf("%s",a);" with "gets(a);" it works fine. Why?
Help is appreciated. Thanks!
Add a space character in:
scanf(" %c",&b);
^
To consume the trailing \n character that is left in stdin after the first scanf.
So a \n is left in the standard input from which scanf is reading. So when a new scanf is met it scans the old \n character.
To neutralize that effect I put a space character in scanf i.e. I am telling it to expect to read a \n or space or \t and then to read a %c.

problem in scanning character in C

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
char ch;
printf("Enter value of a and b");
scanf("%d %d",&a,&b);
printf("Enter choice of operation");
scanf("%c",&ch);// **Here this statment is not able to receive my input***
switch(ch)
{
case '+':
c=a+b;
break;
case '-':
c=a-b;
break;
default:
printf("invalid");
break;
}
getch();
}
Error:
scanf("%c",&ch); // Here this statment is not able to receive my input
Unable to scan input given by user??????
thanks..
Unlike most conversions, %c does not skip whitespace before converting a character. After the user enters the two numbers, a carriage return/new-line is left in the input buffer waiting to be read -- so that's what the %c reads.
Just try
scanf(" %c", &ch);
This is because your scanf is treating the whitespace after the second number as the character to be inserted into ch.
It's getting the newline character from your previous data entry. Look into using fgets() and sscanf() instead of using scanf() directly.
Here in this statement write %s instead of %c. It will surely work.
scanf("%s",&ch);
in this problem you can write like this
scanf(" %c",&ch);
a space will cover your "Enter" character,then it scan's the input that you want...https://ide.geeksforgeeks.org/ANGPHrqeAq
If you're just reading in a single character, you could just use getchar() -
c = getchar();
Use getchar() or sscanf() whichever comforts more.
Like
char ch;
ch = getchar();
This is simple. also if you want to use scanf("%c",&ch); then,
just remove the \n from your previous printf() statement.
For a single character input, use getchar().

Resources