My c program is not giving proper result - c

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.

Related

scanf skipping array position [duplicate]

The following code produces a very strange result when I run it.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
for ( ; ; )
{
char test;
printf("Please enter 'w' ");
scanf("%c", &test);
printf("%c\n", test);
if (test == 'w')
{
printf("Working\n");
}
else
{
printf("ERROR\n");
return 0;
}
}
}
What I want to happen is for the whenever I input 'w' it continues the loop so I can input 'w' again. What it does though is go to the else statement even though I input 'w'. It just seems to skip the scanf() line. I have asked everyone I know who knows C but they do not know how to solve it.
Somebody please help me out here!
This is because you type w followed by ENTER. So there are 2 characters in the input, 'w', followed by a newline (\n). The latter causes the else branch to be taken on the second iteration.
Note that standard input is line buffered when connected to a terminal. If you need to deal with characters immediately, there are ways to do that. See the comp.lang.c FAQ for details ("How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed?").
Note that for robust programming it is a must to check the return value of scanf. It returns the number of successfully converted items. As shown, your code does not handle the case of end-of-file properly, i.e. when the user types Ctrl-D (assuming Unix terminal). Then scanf returns EOF and no conversion was performed, but you use test as if it contained a meaningful value.
as Jens said. you have to ignore the newline '\n'
Adding a space at the beginning of the format specifier " %c" will ignore the newline '\n'
scanf(" %c", &test);
Using " %c" will also ignore other white spaces like \t space \b \v \r
As Jens says, you must consume '\n', use getchar() after scanf()
You need to do something like
scanf("%c", &test);
while(getchar()!='\n');
scanf takes input upto space or \n (whichever comes first) and leaves the \n in the buffer

My code doesn't work when using scanf("%c") [duplicate]

The following code produces a very strange result when I run it.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
for ( ; ; )
{
char test;
printf("Please enter 'w' ");
scanf("%c", &test);
printf("%c\n", test);
if (test == 'w')
{
printf("Working\n");
}
else
{
printf("ERROR\n");
return 0;
}
}
}
What I want to happen is for the whenever I input 'w' it continues the loop so I can input 'w' again. What it does though is go to the else statement even though I input 'w'. It just seems to skip the scanf() line. I have asked everyone I know who knows C but they do not know how to solve it.
Somebody please help me out here!
This is because you type w followed by ENTER. So there are 2 characters in the input, 'w', followed by a newline (\n). The latter causes the else branch to be taken on the second iteration.
Note that standard input is line buffered when connected to a terminal. If you need to deal with characters immediately, there are ways to do that. See the comp.lang.c FAQ for details ("How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed?").
Note that for robust programming it is a must to check the return value of scanf. It returns the number of successfully converted items. As shown, your code does not handle the case of end-of-file properly, i.e. when the user types Ctrl-D (assuming Unix terminal). Then scanf returns EOF and no conversion was performed, but you use test as if it contained a meaningful value.
as Jens said. you have to ignore the newline '\n'
Adding a space at the beginning of the format specifier " %c" will ignore the newline '\n'
scanf(" %c", &test);
Using " %c" will also ignore other white spaces like \t space \b \v \r
As Jens says, you must consume '\n', use getchar() after scanf()
You need to do something like
scanf("%c", &test);
while(getchar()!='\n');
scanf takes input upto space or \n (whichever comes first) and leaves the \n in the buffer

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.

GETS - C is not working for me

I am having trouble with inserting string in to char variable. Problem appeares when I put it into function. When I debug my program, it displays printf but it skipes gets
here is my code:
int uloz(SPRAVA *p){
char string[200];
printf("Your message here: ");
gets(string);
printf("You have entered: %s", string);
getchar();
return 0;
}
Use scanf(" %30[^\n]%*c",string);
[^\n] will accept anything till \n.
30 will limit the length of number of characters to max 30.
initial space(' ') will consume any \n already in stdin stream. (optional & i have not verified it)
& Finally, %*c will consume \n pressed after entering string.
I think, scanf(" %30[^\n]%*[^\n]%*c",string); would be a good option, to discard remaining characters (after 30) that were entered. However this is completely unverified. Just added as a possible idea. Test before use. :-)
There's a newline in the stdio buffer (left over by some previous scanf) so gets is immediately satisfied.
There's no easy way to fix it but you could try discarding input, before the fgets:
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
The true solution is to avoid mixing scanf and fgets.
Use fgets instead of gets.

Interleaving of putchar() and printf() functions [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
It is a statement given in K&R that printf() and putchar() can be interleaved. If it true then why is the following code not giving the required output:-
#include"stdio.h"
void main()
{
char c,d;
printf("Enter the first character\n");
scanf("%c",&c);
printf("%c\n",c);
printf("Enter the second character\n");
d=getchar();
putchar(d);
printf("\n");
}
Whenever I am executing this program, the output is as follows:-
Enter the first character
a
a
Enter the second character
This is the output. This is also happening if I replace printf() by putchar() and scanf() by getchar(). Why is this happpening?
The first scanf leaves in the input buffer the \n resulting from the Return press, so your second getchar() will acquire this \n instead of acquiring another character from the user.
If you want to skip that newline character, you can either instruct the scanf to "eat" it:
scanf("%c\n",&c);
or "eat it" directly with a call to getchar():
scanf("%c",&c);
getchar();
(notice that these are not exactly equivalent, since the second snippet will eat whatever character happens to be in the buffer, while the first one will remove it only if it's a \n)
You can correct your code like this:
#include <stdio.h>
int main() {
char c, d;
printf("Enter the first character\n");
scanf("%c\n", &c); // Ask scanf to read newline and skip
printf("%c\n", c);
printf("Enter the second character\n");
d = getchar();
putchar(d);
printf("\n");
return 0;
}
You are getting two a's because you type one in which is echoed to the console and then you print it out.
flush the stdin before using getchar()..
In turbo, use fflush()..
In gcc, use __fpurge(stdin)..(this is available in <stdio_ext.h> header)..
Flushing the standard input before scanning anything will solve your issue..

Resources