C Program :Error when reading character from stdin using scanf - c

Currently im trying to learn simple C Programs. But, i came into this situation :
#include<conio.h>
#include<stdio.h>
void main()
{
char c;
int tryagain=1;
while(tryagain>0){
printf("Enter the Character : ");
scanf("%c",&c);
printf("You entered the character \"%c\" and the ascii value is %d",c,c);
getch();
clrscr();
tryagain=0;
printf("You want to Trry again Press 1 : ");
scanf("%d",&tryagain);
clrscr();
}
}
The program is fine when user first enter a character. And, when it ask to continue. And, user enter 1 then it is behaving weired. It automatically input blank character and prints the ascii and goto the same place.
How can i resolve this? And, specially, Why is the reason for this?
And, Im sorry about my poor english!
Thank you in Advance.

When you use
scanf("%d",&tryagain);
the number is read into tryagain but the newline character, '\n', is still left on the input stream. The next time you use:
scanf("%c",&c);
the newline character is read into the c.
By using
scanf("%d%*c",&tryagain);
the newline is read from the input stream but it is not stored anywhere. It is simply discarded.

The issue is that you are reading a single number in the second scanf, but user inputs more than a single number there, the user also input a new line character by pressing .
User enters "1\n". Your scanf reads "1", leaving out "\n" in the input stream. Then the next scanf that reads a character reads "\n" from the stream.
Here is the corrected code. I use getc to discard the extra new line character that is there.
#include <stdio.h>
void main()
{
char c;
int tryagain = 1;
while (tryagain > 0) {
printf("Enter a character: ");
scanf("%c", &c);
printf("You entered the character \"%c\" and the ascii value is %d\n", c, c);
tryagain = 0;
printf("If you want to try again, enter 1: ");
scanf("%d", &tryagain);
// get rid of the extra new line character
getc(stdin);
}
}
Also, as a side note, you use conio.h which is not part of standard C, it's MS-DOS header file, thus it's not portable C you are writing. I have removed it from my code, but you might wish to keep it.

Related

Why are the if conditions not being executed?

This is a menu driven program asking for user's choice.
Why are if conditions not executed?
Output is attached.
Creating a program asking for user's input:
void main()
{
float a,b,ans=0;char ch,choice;
choice='y';
while(choice=='Y'||choice=='y')
{
printf("Enter two numbers \n");
scanf("%f %f",&a,&b);
printf("1.+for Addition\n");
printf("2.-for subtraction \n");
printf("3.*for multiplication \n ");
printf("4./for Division \n");
printf("Enter your choice of operation \n");
scanf("%c",&ch);
if(ch=='+')
ans=a+b;
else if (ch=='-')
ans=a-b;
else if(ch=='*')
ans=a*b;
else if(ch=='/')
ans=a/b;
else
{
printf("wrong choice entered\n");
}
printf("Answer is %f \n",ans);
printf("Do you want to coninue (Y/N)\n");
scanf("%c",&choice);
}
printf("program Terminated\n");
}
Output:
/* Enter two numbers
1010
22
1.+for Addition
2.-for subtraction
3.*for multiplication
4./for Division
Enter your choice of operation
wrong choice entered
Answer is 0.000000
Do you want to coninue (Y/N)
n
program Terminated
*/
The above is the output screen.
It doesn't perform operations.
When you input first 2 numbers, they are placed into variables a and b. BUT after entering those 2 numbers, you pressed enter. Computer sees that as new input and place it in first next appropriate variable that requires input. In this case it's your variable ch, and instead of +,-./ or *, ch has value of "new line". If you try to write value of ch on standard output as an integer, it will write number 10. It's ASCII character of new line. Simply adding getchar() after inputting first 2 numbers will collect that new line sign, and your next scanf will work properly.
By the way, you have same problem with your last input scanf("%c",&choice); because pressing enter after previous operation decision, will also cause your program not to work properly. Do the same thing for this part, or simply leave blank character before %c.
Try the following
scanf(" %c",&ch);
^^
and
scanf(" %c",&ch);
^^
Otherwise a next character is read that can be a white space character.
Take into account that according to the C Standard function main without parameters shall be declared like
int main( void )
scanf() does not consume trailing newlines. The skipped scanf() receives the newline from the previous line typed by the user and terminates without receiving more input as you would expect...
scanf() is a bit cumbersome with newlines. A possible solution would be to use fgets() to get a line from the console and then employ sscanf() to parse the received string.
Another, more targeted, solution would be to use " %c" in the format string of the last scanf() call. The %c format specifier does not consume leading whitespace on its own, which is why it gets the remaining newline, rather than a character typed by the user.

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.

Error in C simple program [duplicate]

This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
This is part of a university lab and the TA tells me there is an error but I haven't a clue. When I run it it asks me for the first char but then runs through the program and doesn't ask me at the second scanf.
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
scanf("%c", &sen);
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
scanf("%c", &ben);
printf("The key just accepted is %d", ben);
}
Actually this is C not C++. Save it as file.c.
Try this:
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
sen = getchar();
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
getchar();
ben = getchar();
printf("The key just accepted is %d", ben);
}
Explanation: when you enter the first character and press enter it takes enter's ASCII code as the second.
I suggest not to use scanf. But it works both ways if you put a getchar to "take" the enter.
Adding a space before %c in the second scanf will solve the issue.
This is done because scanf does not consume the \n character after you enter the first character and leaves it in the stdin.As the Enter key(\n) is also a character,it gets consumed by the next scanf call.The space before the %c will discard all blanks like spaces.
When you are scanning a character(%c) using scanf,add a space before %c as it would help reduce confusion and help you. Therefore, in both the scanfs , you can add the space.
When you pressed your key and then hit enter, you typed in two keys. The first was the desired key ,a for example, and the second was the key <enter> typically written as \n. So, your second scanf captures the result \n.
Since printing out the \n character doesn't result in something that is easy to see on the screen, it will appear like your program is just skipping the second scanf and printing out only the fixed parts of the printf without a easily viewable value.
One way to get around this problem is to consume all the key strokes just before the key you want to capture. This is done by accepting more input after the character up until you see a newline character \n. Once you see that character, then you do your next read.
// flush extra input up the to carriage return
char flush = 0;
while (flush != '\n') {
scanf("%c", &flush);
}
// now read my desired input
scanf("%c", &ben);
that's because nobody accepts '\n'. call scanf like this scanf("%c%*c", &sen). %*c means you want to omit one character, which is '\n'.
btw, void main() is allowed. main function is not the real entry point of executable, so it's ok to do that. but it seems not everybody likes it.

Dev-C++ Input skipped

#include<stdio.h>
#include<conio.h>
main()
{
int i;
char c, text[30];
float f;
printf("\nEnter Integer : ");
scanf("%d",&i);
printf("\nEnter Character : ");
c = getch();
printf("\nEnter String:");
gets(text);
printf("\nEnter Float:");
scanf("%f",&f);
printf("\nInteger : %d",i);
printf("\nCharacter : %c8",c);
printf("\nString : %s",text);
printf("\nFloat : %f",f);
getch();
}
Why is this simple program not able to read a string using the gets() function? What else should I use to correct it? Well it it worked in Turbo C in my old 32-bit PC but not here...
Scanf or other input parsing functions take only required quantity of characters as specified in the call from stdin and reject others.As a result these rejected values,during next read of stdin enter into the variables along with the newline characters and thus skipping inputs for a few calls.So its better to call a clear routine that cleans stdin and stops garbage entering into other variables.
Although your code is quite vulnerable still it has solution:-
#include<stdio.h>
int clear()
{
while ((getchar())^'\n');
}
int main()
{
int i;
char c, text[30]={0};
float f;
printf("\nEnter Integer : ");
scanf(" %d",&i);
printf("\nEnter Character : ");
scanf(" %c",&c);
printf("\nEnter String:");
clear();
gets(text);
printf("\nEnter Float:");
scanf(" %f",&f);
printf("\nInteger : %d",i);
printf("\nCharacter : %c",c);
printf("\nString : %s",text);
printf("\nFloat : %f",f);
getchar();
}
With some little research, I guess that the problem comes with scanf(). scanf() reads a line without the end of line character '\n' which seems to stay in the buffer and actually red by the next statement.
alternatively you can use fgets() and sscanf() as follows:
To read a character I used:
fgets(text,sizeof(text),stdin);
sscanf(text,"%c",&c); /* or: c = text[0]; */
to read an integer I have used
fgets(text,sizeof(text),stdin);
sscanf(text,"%d",&i);
I had a major problem with gets() in a C course I had (to which DevC++) was advised as a compiler. However, I totally recall I didn't follow the advice and it turned out that the behavior of fgets() is also compiler dependent.
The man page for gets() has this:
BUGS
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
When you type 42 (or whatever) as the first integer, you actually type three characters: 4, 2 and then the newline character that comes from pressing ENTER. Your first scanf reads an integer, which means that it only reads the 4 and the 2, leaving the newline character in the input buffer.
When your program gets to gets, it reads a the very short line that consists just of that newline character.
You can fix it by reading and throwing away the newline character just after scanf, something like this:
printf("\nEnter Integer : ");
scanf("%d",&i);
while (getchar() != '\n')
;

can any one explain the output of this program?

Why does following program produce two output message at the same time, without asking for any input from the user???
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char input;
do {
printf("Enter a single character: \n");
scanf("%c", &input);
printf("The ordinal value is %d. \n",input);
} while(input != '#');
return 0;
}
The output is followings:
Enter a single character:
s
The ordinal value is 115.
Enter a single character:
The ordinal value is 10.
Enter a single character:
Terminal input is read line at a time unless you specify otherwise; scanf reads one character as specified, leaving the newline you typed afterward to send the line in the input buffer for the next pass of the loop. Consider reading input by lines and using sscanf() or similar to parse those lines.
Just insert getchar(); after your call to scanf. This will eat the newline. The suggestion to use scanf("%c\n", &input); seems sound, but I've never found it to work well; I wonder if anyone can tell me why?

Resources