Weird behaviour of a C program - c

I have been using windows all this time and recently installed Ubuntu on Virtual Box. To give Ubuntu a try,i wrote a simple calculator program.
Here's how it goes:
#include<stdio.h>
float add(float ,float ),sub(float , float ),mul(float ,float ),div(float ,float );
int main()
{
char ch;
float a,b;
printf("Enter an operator: ");
scanf("%c",&ch);
printf("Enter two values: ");
scanf("%f%f",&a,&b);
switch(ch)
{
case '+':
printf("The sum of %f and %f is %f\n",a,b,add(a,b));
break;
case '-':
printf("The substraction of %f from %f is %f\n",a,b,sub(a,b));
break;
case '*':
printf("The multiplication of %f and %f is %f\n",a,b,mul(a,b));
break;
case '/':
printf("The division of %f and %f is %f\n",a,b,div(a,b));
break;
default:
printf("\nEnter a valid operator: \n");
main();
}
return 1;
}
float add(float x,float y)
{
return (float)x + y;
}
float sub(float x,float y)
{
return (float)x-y;
}
float mul(float x,float y)
{
return (float) x*y;
}
float div(float x,float y)
{
return (float) x/y;
}
when i enter an invalid operator,it should actually read the operator and values again. But, it's asking for values directly without reading the operator. Here's a picture:
So what am i doing wrong? please explain. Thanks in advance!

You did not ignore the newlines in your inputs.
Change
scanf("%c", &ch);
to
scanf(" %c", &ch);
and try again.
When you input 3<enter>, that 3 will be consumed by the second %f, but that <enter> (i.e. newline) will still in the input buffer, and the %c in the first scanf() will consume this newline. The space in %c will ignore that newline in the input buffer.
$ ./a.out
Enter an operator: h
Enter two values: 2
3
Enter a valid operator:
Enter an operator: +
Enter two values: 2
3
The sum of 2.000000 and 3.000000 is 5.000000

Related

How to make so that code will ask me what it want to do [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
How to do scanf for single char in C [duplicate]
(11 answers)
Scanf skips every other while loop in C
(10 answers)
Closed 4 months ago.
i created a code that converts the temperature into another form, like if you want to convert celcius to farenheit or kevlin and vice versa. But it isnt working as i thought.
code:-
#include <stdio.h>
int main()
{
float a, b;
char c, e;
printf("What you want to change\ntype c for celcius, f for farenheit or k for kelvin: ");
scanf("%c", &c);
switch (c)
{
case 'c':
printf("Now put the celcius value you want to convert: ");
scanf("%f", &a);
printf("Now in which you want to change\ntype f for farenheit or k for kelvin: ");
scanf("%c", &e);
switch (e)
{
case 'f':
printf("The farenheit value of %0.2f degree celcius: %0.2f\n", a, a*1.8+32);
break;
case 'k':
printf("The kelvin value of %0.2f degree celcius: %0.2f\n", a, a+273.15);
break;
default:
printf("You didnt put the correct operation");
break;
}
break;
case 'f':
printf("Now put the farenheit value you want to change into celcius: ");
scanf("%f", &a);
b = ((a-32)*5)/9;
printf("Now in which you want to change\ntype c for celcius or k for kelvin: ");
scanf("%c", &e);
switch (e) {
case 'c':
printf("The celcius value of %0.2f degree farenheit: %.2f\n", a, b);
break;
case 'k':
printf("The kelvin value of %0.2f degree farenheit: %0.2f\n", a, b+273.15);
break;
default:
printf("You didnt put the correct operation");
break;
}
break;
case 'k':
printf("Now put the kelvin value you want to change: ");
scanf("%f", &a);
if (a>=0) {
printf("Now in which you want to change\ntype c for celcius or f for farenheit: ");
scanf("%c", &e);
b=(a-273.15)*1.8+32;
switch (e) {
case 'c':
printf("The celcius value of %0.2f kelvin in celcius is: %0.2f\n", a, a-273.15);
break;
case 'f':
printf("The farenheit value of %0.2f kelvin in farenheit is: %0.2f\n", a, b);
break;
default:
printf("You didnt put the correct operation");
break;
}}
else {
printf("Kelvin cannot be less than zero");
}
break;
default:
printf("You didnt put the correct spell of what you want to change\n");
break;
}
return 0;
}
I was trying to make it so that it will ask the user in which you want to change but it didnt worked as i thought. It isnt asking for what you want to change and skips that scanf function.
The issue you're getting is that scanf leaves a newline character in the buffer after getting the float. Then the scanf for the character gets the newline and you're switch statement goes to the default statement. This is a major flaw of scanf and can be very confusing for new users of C. One potential solution to this is to clear the buffer using this:
while ((c = getchar()) != '\n' && c != EOF);
This uses getchar (which takes one character from the same buffer as scanf) and will loop until getchar gets a newline or gets to the end of the buffer. Then when you run scanf it will have an empty buffer an take input from the user.

C for loop runs good first iteration only the next iteration it ignores scanf in loop

I'm trying to write calculator code in C for loop. The problem it runs good at first iteration only. the next iterations it ignores scanf command so it gives wrong output.
#include <stdio.h>
#include <stdlib.h>
int main(){
int i ;
char operator_;
double x, y;
for (i = 1; i <= 3; ++i)
{
printf("Enter an operator (+, -, *,/): ");
scanf("%c",&operator_);
printf("\nEnter the first number: ");
scanf("%lf",&x);
printf("Enter the second number: ");
scanf("%lf",&y);
switch (operator_) {
case '+':
printf("The sum equals to %lf + %lf = %lf\n\n\n", x, y, x + y);
break;
case '-':
printf("The difference equals to %lf - %lf = %lf\n\n\n", x, y, x - y);
break;
case '*':
printf("The product equals to %lf * %lf = %lf\n\n\n", x, y, x * y);
break;
case '/':
printf("The quotient equals to %lf / %lf = %lf\n\n\n", x, y, x / y);
break;
default:
printf("Error! operator is not correct\n\n\n");
}
}
printf("\nyour trial period has ended\n\n\n");
return 0;
}

How to solve this infinite loop problem in C program I am facing?

I am getting an infinite loop for the program shown below when I run it twice without giving input for the first time. But when I give input on the first run then it is working perfectly.
But if I run it once and don't give input and rerun it, it results in an infinite loop.
How can I resolve the issue?
I am using VS Code.
Source code:
/* UNIT CONVERSION
kms to miles
inches to foot
cms to inches
pound to kgs
inches to meters
*/
#include <stdio.h>
int main(int argc, char const *argv[])
{
int x;
float a;
start:
printf("\nSelect the type of unit conversion you want\nkms to miles\tPRESS 1\ninches to foot\tPRESS 2\ncms to inches\tPRESS 3\npound to kgs\tPRESS 4\ninches to meters\tPRESS 5\nPRESS 0 TO EXIT\n");
scanf("%d", &x);
switch (x)
{
case 0:
goto end;
case 1:
printf("Enter the value in Km to be converted into miles\n");
scanf("%f", &a);
printf("%f kms is %f miles\n", a, 0.621371 * a);
goto start;
case 2:
printf("Enter the value in inches to be converted to foot\n");
scanf("%f", &a);
printf("%f inches is %f feet\n", a, 0.0833333 * a);
goto start;
case 3:
printf("Enter the value in cms to be converted to inches\n");
scanf("%f", &a);
printf("%f cms is %f inches\n", a, a * 0.393701);
goto start;
case 4:
printf("Enter the value in pound to be converted to kgs\n");
scanf("%f", &a);
printf("%f pound(s) is equal to %f kgs", a, a * 0.453592);
goto start;
case 5:
printf("Enter the value in inches to be converted to metres\n");
scanf("%f", &a);
printf("%f inch(es) is equal to %f metre(s)", a, a * 0.0254);
goto start;
default:
printf("You have not entered a valid input :(\n");
goto start;
}
end:
printf("You have successfully exited the program\n");
return 0;
}
If you don't give any input, by which you probably mean you just hit enter, scanf fails and the x variable will not be set.
if (scanf("%d", &x) != 1) {
x = -1;
}
This will set x to an invalid value in case no number was given. The code checks that scanf actually made exactly 1 conversion.
Always check scanf made the number of conversions requested.
And stop using goto. Use proper while, for, or do while loops.

How to terminate a program using while loop [duplicate]

This question already has answers here:
Why do interleaved scanf() + printf() statements result in both scanf() calls executing first, then both printf() calls?
(2 answers)
Closed 5 years ago.
I have made this calculator.
Everything works fine.
However, I want to use a while loop as follows:
char cont = 'y'
while (cont == 'y') {
/code/
}
printf("Do you want to continue (y/n)")
scanf("%c", & cont)
This prints:
Do you want to continue (y/n)
But when I enter something the program ends unexpectedly.
Full Code:
#include < stdio.h >
#include < conio.h >
void main() {
float x, y, result;
int select;
char cont = 'y';
clrscr();
while (cont == 'y') {
clrscr();
printf(
"Please Enter The Respective Number For Following Operation\n1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n"
);
scanf("%d", & select);
clrscr();
switch (select) {
case 1:
{
printf("\nEnter The First Number To Add\n");
scanf("%f", & x);
printf("\nEnter The Second Number To Add\n");
scanf("%f", & y);
clrscr();
result = x + y;
printf("Addition of two numbers %f and %f is %f", x, y,
result);
break;
}
case 2:
{
printf("\nEnter The First Number To Subtract\n");
scanf("%f", & x);
printf("\nEnter The Second Number To Subtract\n");
scanf("%f", & y);
clrscr();
result = x - y;
printf("Subtraction of two numbers %f and %f is %f", x, y,
result);
break;
}
case 3:
{
printf("\nEnter The First Number To Multiply\n");
scanf("%f", & x);
printf("\nEnter The Second Number To Multiply\n");
scanf("%f", & y);
clrscr();
result = x * y;
printf("Multiplication of two numbers %f and %f is %f", x,
y, result);
break;
}
case 4:
{
printf("\nEnter The Numerator\n");
scanf("%f", & x);
printf("\nEnter The Denominator\n");
scanf("%f", & y);
clrscr();
result = x / y;
printf("\nDivision of two numbers %f and %f is %f", x, y,
result);
break;
}
default:
{
printf("Invalid Choice");
break;
}
}
printf("\n\nCalculator By XXX\n\nDo you want to Continue (y/n)\n");
scanf("%c", & cont);
}
getch();
}
Your while loop terminates because the scanf("%c",&cont); reads the leftover \n from the buffer which makes your while statement to fail.
You should modify your scanf to scanf(" %c",&cont);.
Put that scanf statement inside while loop or you can use do..while loop in place of while.
do {
// code
printf("Do you want to continue (y/n)"); scanf("%c",&cont);
} while(cout=="y");

What's wrong with this C program?

I've written a special calculator which prompts the user for 2 numbers then displays a menu which basicly asks the user what to do with that input. It works great however no matter what numbers I input the result is 0. What am I doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
char a, rad, patrat;
float x, y, media, radical, pat1, pat2;
patrat = 253;
rad = 251;
loop:
printf("Input 2 numbers...\n");
scanf("%f %f", &x, &y);
media = (x+y)/2;
radical = sqrt(x+y);
pat1 = x*x;
pat2 = y*y;
loop2:
printf("\n \nA - Arithmetic media.\n");
printf("B - Square root.\n");
printf("C - Sqare of the 2 numbers.\n");
printf("D - Write other numbers.\n");
printf("E - Terminate the program.\n");
a = getch();
switch(a) {
case'a':
system("cls");
printf("Media of the 2 numbers is %f", &media);
goto loop2;
case'b':
system("cls");
printf("%c%f + %f = %f", &rad, &x, &y, &radical);
goto loop2;
case'c':
system("cls");
printf("%f%c = %f, %f%c = %f", &x, &patrat, &pat1, &y, &patrat, &pat2);
goto loop2;
case'd':
goto loop;
case'e':
return 0;
}
}
You're using & in your printf statements, you shouldn't be. Scanf has it as it's writing so takes pointers.
Why are you using the operator & to your printf arguments?
printf doesn't take pointer arguments for %f conversion specification
float b;
scanf("%f", &b);
but
float a = 42;
printf("%f\n", a);
printf("Media of the 2 numbers is %f", &media);
should be
printf("Media of the 2 numbers is %f", media);
similarly for all other printf()
Generally goto statements are considered harmful when they are called backwards! So please avoid them. The same functionality can be done by a while(1) for for(;;) loop with proper termination condition.
In your printf statement, you are using
printf("Media of the 2 numbers is %f", &media);
&media is the address of your variable media.
In scanf, we provide the address of the variable as parameter so that it stores the values at that address. But in printf, we provide the variable value and not the variable address. If you provide variable address then it would print the address and not the value.
So the correction should be
printf("Media of the 2 numbers is %f", media);

Resources