c - char variable proceeds without taking input - c

I have written a program to take input of two numbers and either add or subtract the numbers depending the operation specified.
Here is my code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
float i, j, k;
char a;
printf("This is a program to add or subs two number.\n");
printf("Enter the first number : ");
scanf("%f", &i);
printf("Enter the second number : ");
scanf("%f", &j);
printf("Give your choice(+ or -): ");
scanf("%c", &a);
switch(a){
case '+' :
k = i + j;
printf("Sum = %f\n", k);
break;
case '-' :
k = i - j;
printf("Difference = %f\n", k);
break;
default:
printf("Cannot do this operation\n");
}
return 0;
}
This program takes input for the two numbers but skips input for operation and runs the default case. Please help!
(I am using gcc compiler).

The %c conversion specifier won't automatically skip any leading whitespace, so if there's a stray newline in the input stream (from a previous entry, for example) the scanf call will consume it immediately.
One way around the problem is to put a blank space before the conversion specifier in the format string:
scanf(" %c", &a);
The blank in the format string tells scanf to skip leading whitespace, and the first non-whitespace character will be read with the %c conversion specifier.
-Aditya

Related

getchar following scanf (to read an integer) takes terminating "enter" key of scanf as character

When I have a scanf followed by a getchar, why does the getchar always keep getting the last delimiting character of scanf? How can I stop that? I tried looking into "format specifiers" for scanf, read quite a few things but none solves this.
The code is shown below -
#include <stdio.h>
#include <conio.h>
int main()
{
int a;
char b;
printf ("Enter an integer \n");
scanf_s(" %d", &a);
printf("Enter a character \n");
b = getchar();
printf("The integer you entered is %d \n", a);
printf("The character you entered is %c \n", b);
_getch();
return 0;
}
The output is as below -
Enter an integer
4563
Enter a character
The integer you entered is 4563
The character you entered is
The enter key I press at the end of integer entry is being returned by getchar. The screen does not even stop after printing "Enter a character". What is the correct way to do this ?
Use the scanf(" %c", &b) instead of getchar()
When you put the space befor the %c you clean the buffer
Or you can clean the buffer using this too:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
Complete example:
int main(void)
{
printf("Enter an integer \n");
int a;
scanf(" %d", &a);
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
}
printf("Enter a character \n");
char b = getchar();
printf("The integer you entered is %d \n", a);
printf("The character you entered is %c \n", b);
_getch();
}
But I think the scanf()

scanf function not working with characters

I was just trying out a simple program in C, inserting into an array.
I used a scanf function to accept characters but it seems the compiler just skipped that and just went to end of the program.
This was the code that I used :-
#include <stdio.h>
void main()
{
int a[50], i, j, m, n, x;
char ch;
printf("Enter the no. elements of the array :- ");
scanf("%d", &m);
printf("Enter the elements below :- ");
for (i = 0; i < m; i++)
{
scanf("%d", &a[i]);
}
printf("The array is :- \n");
for (i = 0; i < m; i++)
{
printf("%d", a[i]);
}
printf("\nDo you want to enter an element ? (Y/N)\n");
scanf("%c", &ch); // The compiler just skips this along with the
while (ch == 'y' || ch == 'Y') // while loop and goes straight to the printf
{ // statement
printf("The index of the element :- ");
scanf("%d", &n);
printf("\nEnter a number :- ");
scanf("%d", &x);
for (i = m; i > n; i--)
{
a[i] = a[i - 1];
}
a[n] = x;
printf("\nInsert more numbers ? (Y/N)");
scanf("%c", &ch);
m = m + 1;
}
printf("\nThe array is :- ");
for (i = 0; i < m; i++)
{
printf("%d", a[i]);
}
}
I used the variable ch in order to allow the user to have a choice, whether or not to insert elements i.e. Y or N.
But the compiler basically skips the third scanf function, the one that accepts the char, along with the while loop.
I just want to know why the scanf function was skipped ?
Back to the previous scanf which is the last array member.
scanf("%d",&a[i])
In the input file if you entered:
32\n
^^
input will wait just before the newline after reading the decimal number.
In the scanf which causes problem:
scanf("%c", &ch);
It will read the newline character as it is available in input that's why it will skip that line after being executed implicitly.
To ignore the whitespace you have only to add space before the specifier %c as stated in comment by #xing and #WeatherVane.
scanf(" %c",&ch);
C99 7.19.6.2
Input white-space characters (as specified by the isspace function)
are skipped, unless the specification includes a [, c, or n
specifier.250)

Getting multiple character inputs inside for loop

char c;
int i;
for(i=0;i<5;i++)
{
printf("Enter a character : ");`
scanf("%c",&c);
}
getch();
The above code doesn't work properly.It is getting input for only 3 times. I am not able to find solution for it.Please help with it.Thanks in advance !!
This is because of the new-line character \n left behind by the previous scanf is read by the scanf in the next iteration. Place a space before the %c specifier to consume the \n
scanf(" %c",&c);
^Notice the space
char c is a single character variable.
In your code, your are reading time and time again characters and storing it into c, effectively overwriting it each time. If you would like to input multiple characters, consider using a character array likewise:
#include <stdio.h>
int
main (void)
{
char c[5];
int counter;
for (counter = 0; counter < 5; counter++)
{
printf ("Enter a character: ");
scanf ("%c\n", &c[i]);
}
printf ("The string you input is %s\n", c);
return 0;
}
Suppose you enter a, b and c on the screen then it is actually taking 5 inputs
Input 1: a
Input 2: \n
Input 3: b
Input 4: \n
Input 5: \n
The newline is also taken as input

Why does this C program completely skip my input?

CODE:
#include <stdio.h>
main() {
int nums[100], i;
char answer;
int count = 0;
double avg;
for (i = 0; i < 100; i++) {
printf("Enter number %d: ", i + 1);
scanf("%d", &nums[i]);
printf("Another? ");
scanf("%c", &answer);
count += nums[i];
}
}
RUN:
~> a.out
Enter number 1: 1
Another? Enter number 2: 2
Another? Enter number 3: 3
Another? Enter number 4: 4
Another? Enter number 5: 5
Another? Enter number 6: 6
Another? Enter number 7: 7
Another? Enter number 8: 8
Another? Enter number 9:
It's supposed to ask me if I want to enter another number, but for some reason the scanf is not working. Also, I need to make it so that the user can enter 100 numbers, or any number under that, being prompted with a question of "do you want to enter another number". If the answer is no, it terminates, if it is yes, it carries on.
Your first scanf leaves a newline in the buffer. It's because %d ignores trailing blanks while %c doesn't. Use this cheap trick to make the second scanf eat the blanks:
scanf(" %c", &answer);
^
The issue is common enough, you can read more about it in the C FAQ.
You need a space before the %c in order to skip the newline that wasn't read when scanf stopped at the end of the number.
I have some unsolicited advice...
Don't use scanf(3) directly, it's too hard to make it do what you want. It's usually better to use fgets(3) and then sscanf(3).
Compile with warnings turned on. (On my Mac that means cc -Wall ...)
And with warnings turned on, here your program with a few issues fixed:
#include <stdio.h>
int main(void) {
int nums[100], i;
char answer;
int count = 0;
// double avg;
for (i = 0; i < 100; i++) {
printf("Enter number %d: ", i + 1);
scanf(" %d", &nums[i]);
printf("Another? ");
scanf(" %c", &answer);
if (answer != 'y' && answer != 'Y')
break;
count += nums[i];
}
return 0;
}

My program is not asking for the operator the second time

#include<stdio.h>
#include<stdlib.h>
main(){
int b,c,r,d;
char a;
while(1){
printf("Enter the operator\n");
scanf("%c",&a);
if(a=='+') d=1;
if(a=='-') d=2;
if(a=='&') d=3;
if(a=='|') d=4;
if(a=='.') d=5;
printf("Enter the operands\n");
scanf("%d",&b);
scanf("%d",&c);
switch(d){
case 1:r=c+b;
break;
case 2:r=c-b;
break;
case 3:r=c&b;
break;
case 4:r=c|b;
break;
case 5:exit(0);
deafult:printf("Enter a valid operator");
}
printf("Result = %d\n",r);
}
}
Output:
Enter the operator
+
Enter the operands
8
7
Result = 15
Enter the operator
Enter the operands
scanf("%d",... will read a number (skipping whitespace beforehand) but leave the newline on the input stream. scanf("%c",... will read the first character, and does not skip whitespace.
One simple modification is to use
scanf(" %c", &a);
This will tell scanf to skip any whitespace before the character.
That because of the function scanf width param "%c", after the 1st time loop, at line scanf("%d",&c);, like +, there's a end-line character in the input stream, then the second loop, scanf get the end-line character as the input and parse it to a;
To fix this, you can add a scanf("%c"); line right after scanf("%d",&c);
have a look at
scanf error in c while reading a character

Resources