How to read three variables using scanf in C? - c

I am writing a simple calculator. I want to read first integer and save it in el1. Then I want to print "Enter el2: \n" and after this read the second integer and save it in el2. After this I need to print "Choose from ( + , - , / , * )" and read it and save in op[0]. My program is printing Enter el1: and then it waits for me to input 2 integers, then it pronts Enter el2: and waits for me to input 1 integer and then prints Choose from.. and reads nothing.
int el1 = 0;
printf("Enter el1: \n");
scanf(" %d \n", &el1);
int el2 = 0;
printf("Enter el2: \n");
scanf(" %d \n", &el2);
printf("Choose from ( + , - , / , * ):\n");
char op[2];
scanf("%c", &op[0]);
How to make it work properly?

as mentioned in comments remove white spaces from scanf .otherwise it will wait for you to enter a non-white space character.
and add one space here scanf(" %c", &op[0]); , because it prevent scanf to take \n in buffer as input.
look
printf("Enter el1: \n");
scanf("%d", &el1);
int el2 = 0;
printf("Enter el2: \n");
scanf("%d", &el2);
printf("Choose from ( + , - , / , * ):\n");
char op[2];
scanf(" %c", &op[0]);

Related

How can I store and print a character input?

I am familiar with storing and printing characters using getchar(); and putchar();.
However, when I use it with my entire code, it does not seem to work. In the command window, it will take the character, but not print it. Thus, I have no idea what the computer is doing. I tried the code for storing and printing a character on its own and it works fine.
int ans;
printf("\n\t Would you like to remove an item from your cart? (Y or N): ");
ans = getchar();
printf("\n\t ");
putchar(ans);
But as soon as I use it with the entire code, it does not work properly.
#include <stdio.h>
void main()
{
float items[6];
float sum;
float taxSum;
printf("\n\n\n\n");
printf("\t Please enter the price for Item 1: ");
scanf_s(" %f", &items[0]);
while (!((items[0] >= 0.001) && (items[0] <= 999.99)))
{
printf("\n\t [ERROR] Please enter number between $0.01 and $999.99: ");
scanf_s(" %f", &items[0]);
}
int ans;
printf("\n\t Would you like to remove an item from your cart? (Y or N): ");
ans = getchar();
printf("\n\t ");
putchar(ans);
I'm extremely curious as to why that is and what I need to do to get it work.
Use
char ans;
printf("\n\t Would you like to remove an item from your cart? (Y or N): ");
scanf( " %c", &ans );
^^^^^
ans = toupper( ( unsigned char )ans );
putchar( ans );
See the leading space in the format string. It allows to skip white space characters as for example the new line character '\n' that corresponds to the pressed Enter key.
Or as #chux - Reinstate Monica wrote in his comment instead of declaring the variable ans as having the type char you can declare it with the type unsigned char. For example
unsigned char ans;
printf("\n\t Would you like to remove an item from your cart? (Y or N): ");
scanf( " %c", &ans );
^^^^^
ans = toupper( ans );
putchar( ans );

I couldn't input the character value in c [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 2 years ago.
MY CODE:
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf("%c",&g1);
printf("\nEnter the grade of student 2: ");
scanf("%c",&g2);
printf("\nEnter the grade of student 3: ");
scanf("%c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
OUTPUT:
Enter the grade of student 1: A
Enter the grade of student 2:
Enter the grade of student 3:
//I am getting a line break and couldn't enter the value of student 2 and the cursor moves to student 3!!
Try doing:
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf(" %c",&g1);
printf("\nEnter the grade of student 2: ");
scanf(" %c",&g2);
printf("\nEnter the grade of student 3: ");
scanf(" %c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
Sorry, I'm new to this.
Just give a space before %c in scanf to get desired input. The below is your own code where I've added space in the second and third scanf statements.
#include<stdio.h>
char main()
{
char g1,g2,g3;
printf("Enter the grade of student 1: ");
scanf("%c",&g1);
printf("\nEnter the grade of student 2: ");
scanf(" %c",&g2);
printf("\nEnter the grade of student 3: ");
scanf(" %c",&g3);
printf("%c%c%c",g1,g2,g3);
return 0;
}
And well, the reason? If you don't, then the next scanf statement assumes the new line you create by pressing "Enter" as a new character, which is \n. So we add a space in scanf to let the statement know that space is not considered an input.
It is often easier to always read an entire line, like this:
#include <stdio.h>
void ReadLine(char result[], int resultLen)
{
int ch, i;
i = 0;
ch = getchar();
while ((ch != '\n') && (ch != EOF)) {
if (i < resultLen - 1) {
result[i] = ch;
i++;
}
ch = getchar();
}
result[i] = '\0';
}
int main(void)
{
char g1[2], g2[2] ,g3[2];
printf("Enter the grade of student 1: ");
ReadLine(g1, sizeof g1);
printf("Enter the grade of student 2: ");
ReadLine(g2, sizeof g2);
printf("Enter the grade of student 3: ");
ReadLine(g3, sizeof g3);
printf("%s%s%s\n", g1, g2, g3);
return 0;
}
first Scanf will not read/flush the "\n" after reading the single char.
this character on input buffer will make the 2nd and 3rd scanf to get execute and fail without actually prompting the user.
There are multiple ways to handle this.
read complete line
use gets/fgets to rad complete inputline
then use scanf to read from buffer
eg:
fgets(buff, 255, stdin);
sscanf(buff, "%c", &value);
execute a char read after every scanf statement.
getch()
Put a preceeding " " in front of every "%c" used in scanf.
this will skip the special char.
"scanf(" %c", &value);"

Why does the space is required before %c in order to make the code work?

THAT'S REALLY INTERESTING
wrong code
#include <stdio.h>
int main( )
{
char another;
int num;
do
{
printf("Enter a number: ");
scanf("%d", &num);
printf("\nWant to enter another number y/n ");
scanf("%c", &another);
}while(another == 'y');
return 0;
}
OUTPUT:
Enter a number: 23
Want to enter another number y/n
C:\Users\Shivam Singh\Documents\Let's C\From Book\Ch3>
To differentiate between the wrong and right code please look at the %c. The only difference in both the codes is a space which is just before %c in the right code.
right code
#include <stdio.h>
int main( )
{
char another;
int num;
do
{
printf("Enter a number: ");
scanf("%d", &num);
printf("\nWant to enter another number y/n ");
scanf(" %c", &another);
}while(another == 'y');
return 0;
}
OUTPUT:
Enter a number: 23
Want to enter another number y/n y
Enter a number: 54
Want to enter another number y/n n
The space is required for scanf() to consume the pending newline left in stdin by the previous scanf() that read a number and stopped consuming characters right after the last digit. Without this space, scanf() will store the next byte into another, most likely the newline that was typed by the user to submit the number.
Note that you should also test the return values of scanf()to detect invalid input or premature end of file.

C language: The Array did not return a correct value

I have an assignment in C language that requires to ask users to enter values to arrays. My idea is createing two different arrays which one contains integer values and the other holds character values. This is my code so far:
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type");
printf(" and Time Input:");
scanf("%c", &instrType[0]);
scanf("%d", &time[0]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
while (continued == 'Y' || continued == 'y')
{
printf("\nL-lock a resource");
printf("\nU-unlock a resource");
printf("\nC-compute");
printf("\nPlease Enter The Instruction Type ");
printf("Time Input:");
scanf("%c", &instrType[i]);
scanf("%d", &time[i]);
printf("\nContinue? (Y/N) ");
scanf("%s", &continued);
i = i + 1;
}
return 0;
}
The expected value should be: L1 L2 C3 U1
My Screenshot
The loop just stopped when I tried to enter new values and the condition did not check the value even I entered 'Y' meaning 'yes to continue' please help :(
You are comparing a string with a character that is instead of using scanf("%s",&continued) try using "%c"
The main problem is scanf("%c", &char) because scanf() after had read the input print a \n to pass at the next line, this cause that the next scanf() instead of reading your input, go to read \n, causing the failure in the reading of the input.
To avoid this problem put a space before %c ==> scanf(" %c", &char)
#include <stdio.h>
int main()
{
char continued;
int i = 0;
char instrType[10];
int time[10];
do
{
printf("L-lock a resource\n");
printf("U-unlock a resource\n");
printf("C-compute\n");
printf("Please Enter The Instruction Type and Time Input: ");
scanf(" %c%d", &instrType[i], &time[i]);
printf("Continue? (Y/N) ");
scanf(" %c", &continued);
i++;
} while (continued == 'Y' || continued == 'y');
return 0;
}
Other things:
Instead of i = i + 1 you can use i++
Instead of using a while() is better using a do{...}while() for saving some line of code.
You can concatenate more inputs in a single line ==> scanf(" %c%d", &instrType[i], &time[i])

C: Multiple input from keyboard

I'm trying to read multiple input from keyboard and store the input in variables.
A snipet of my code:
char answer = 'N';
int artnr;
char artname [27];
int stock;
double price;
while (answer != 'Y') {
printf("%s\n", "Enter article number:");
scanf("%d" , &artnr);
printf("%s\n", "Enter article name:");
scanf("%c" , &artname);
printf("%s\n", "Enter stock balance:");
scanf("%d" , &stock);
printf("%s\n", "Enter a price");
scanf("%f" , &price);
printf("%s\n", "Do you want to quit? (Y/N)");
scanf("%c" , &answer);
}
Output:
Enter article number:
1
Enter article name:
Enter stock balance:
25
Enter a price
4
Do you want to quit? (Y/N)
Enter article number:
Something seems to go wrong with my scanning. I guess it has to with the '/o' in the article name or when I press enter in order to confirm my input.
artname is a char array and "Enter article name:" suggests you actually wanted to scan a string.
So, this
scanf("%c" , &artname);
probably should be
scanf("%s", artname);
scanf() leaves the trailing newline when you scan with %c in the input buffer. You can ignore it by adding a whitespace in the format string:
scanf("%c" , &answer);
to
scanf(" %c" , &answer); // Notice the space in " %c"
A whitepsace in the format string tells scanf() to ignore any number of whitespaces in the input.
and change this
scanf("%f" , &price);
to
scanf("%lf" , &price);
in order to match the format string with the type.

Resources