Simple IF statement scanf - c

For an assignment I was asked to create a small program which asks for the users input which determines the converter they wish to operate. My question is why doesn't the program ask for the users input, AFTER they have entered which convertor they wish to use (1 or 2). Instead of calling scanf, it just runs the entire statement in one go.
#include <stdio.h>
int main()
{
float cm;
float inches;
int operation;
printf("Hello and welcome to the Inches to Centimetres converter. \n");
printf("Choose from the options below by entering the corresponding number:\n");
printf("Inches to CM converter (1)\n");
printf("CM to Inches converter (2)\n");
scanf("&d", &operation);
if (operation == 1)
{
printf("Please enter the amount of Inches you wish to convert : \n");
scanf("%f", &inches);
cm = inches * 2.54;
if (inches <= 0)
{
printf("Invalid number");
}
else
printf("%f inches is equal to %f centimetres.", inches, cm);
}
else if (operation == 2);
{
printf("Please enter the amount of Centimetres you wish to convert : ");
scanf("%f", &cm);
inches = cm / 2.54;
if (cm <= 0)
{
printf("Invalid number");
}
else
printf("%f centimetres is equal to %f inches.", cm, inches);
}
}
Output

Two problems here. First:
scanf("&d", &operation);
There's a typo, "&d" should be "%d", and it's why you get prompted twice right away. You want:
scanf("%d", &operation);
Second is this:
}
else if (operation == 2);
{
The ; immediately ends the else block. So the block in braces will always run. Get rid of the ;
}
else if (operation == 2)
{
Better yet:
} else if (operation == 2) {
Formatting your braces this way will practically eliminate this type of error.

Related

Issues with do while loop

The code allows you to choose between star and delta resistive network conversions. There is also an exit option. I wanted to validate the values for R_a, R_b, R_c etc. however, I have run into some trouble with my do while loop. The lower limit is 1000 and the upper is 1000000.
I intend to have the program carry on if the input is within range and prompt for another input from the user if it is not. However, as of now, the program continues if the value is within range, but also continues after giving a warning when it is not - when I want it to loop back to the first input prompt.
Once correct, I will add the loop to all inputs.
If anyone is able to fix/find the issue, it would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
printf("\n\n\t\tDelta and Star Converter\n\n\n");
int choice, num, i;
unsigned long int fact;
while(1)
{
printf("1. Star \n");
printf("2. Delta\n");
printf("0. Exit\n\n\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:;
float R_a=0,R_b=0,R_c=0,R_ab,R_bc,R_ac;
printf("Please enter the value of the Star connected resistors:\n");
do {
printf("R_a = ");
scanf("%f",&R_a);
if (R_a > 1000000) {
printf("Please");
} else if (R_a < 1000) {
printf("Number to low\n");
}else {
}
}while(R_a = -0);
printf("R_b = ");
scanf("%f",&R_b);
printf("R_c = ");
scanf("%f",&R_c);
R_ab=R_a+R_b+(R_a*R_b)/R_c;
R_bc=R_b+R_c+(R_b*R_c)/R_a;
R_ac=R_a+R_c+(R_a*R_c)/R_b;
printf("the equivalent Delta values are: \n");
printf("R_ab = %.2f Ohms\n",R_ab);
printf("R_bc = %.2f Ohms\n",R_bc);
printf("R_ac = %.2f Ohms\n",R_ac);
break;
case 2:;
printf("Please enter the values of the Delta connected resistors:\n");
printf("R_ab = ");
scanf("%f",&R_ab);
printf("R_bc = ");
scanf("%f",&R_bc);
printf("R_ac = ");
scanf("%f",&R_ac);
R_a = (R_ab*R_ac)/(R_ab + R_bc + R_ac);
R_b = (R_ab*R_bc)/(R_ab + R_bc + R_ac);
R_c = (R_ac*R_bc)/(R_ab + R_bc + R_ac);
printf("the equivalent Star values are: \n");
printf("R_a = %.2f Ohms\n",R_a);
printf("R_b = %.2f Ohms\n",R_b);
printf("R_c = %.2f Ohms\n",R_c);
break;
case 0:
printf("\n\nAdios!!\n\n\n");
exit(0); // terminates the complete program execution
}
while (0) ; }
printf("\n\n\t\t\tThank you!\n\n\n");
return 0;
}
while(R_a = -0)
= is the assignment operator. This assigns -0 to R_a, and evaluates to the same falsy value, ending the loop.
Change the do ... while to an infinite loop, and break the loop when the value is in range.
while (1) {
printf("R_a = ");
if (1 != scanf("%f", &R_a))
exit(EXIT_FAILURE);
if (R_a > 1000000) {
fprintf(stderr, "Number too high.\n");
} else if (R_a < 1000) {
fprintf(stderr, "Number to low.\n");
} else {
break;
}
}

How do I keep my program asking me info until I tell him to stop?

Im making a calculator with A LOT of functions, Im not nearly done with the functions. But I thought, I want the program active after returning me the value I asked for. My logic was to put it into a while loop, but clearly my idea and how I put it are not equal. Or maybe my logic doesnt work in this case. Anyway, imagine I ask the program how much its 2+2 and it returns me 4. Done, but I want it to ask me again for another operation, how can I do that?
Im really new with this stuff, so thanks for the help.
To resume the code below. I ask for a value, then scan it, then ask for a operator, then I ask wether if the user want to continue or not, if he says yes thats the condition for the loop ---> while(condition != 'yes' );{
And if not, just end the program. And I putted the operations inside the loop.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int input;
double sinus;
int op;
printf(" What function do you want to use? \n \n --------------------------------------- \n");
printf(" BASIC OPERATIONS --> type 1 \n --------------------------------------- \n");
printf(" TRIGONOMETRIC FUNCTIONS \n sin --> type 2 \n cos --> type 3 \n tan --> type 4 \n arcsin --> type 5 \n arccos --> type 6 \n arctan --> type 7 \n --------------------------------------- \n");
scanf("%d", &op);
char condition[5];
printf("Stop? Type: yes or no");
scanf("%s", &condition);
while(condition != 'yes' );{
if (op == 1) {
double val1;
char op1;
double val2;
printf("Please type a number: \n" );
scanf("%lf", &val1);
printf("Please type an operator: \n" );
scanf(" %c", &op1);
printf("Please type another number: \n" );
scanf("%lf", &val2);
if (op1 == '+') {
printf("%f \n", val1 + val2);
}
if (op1 == '-') {
printf("%f \n", val1 - val2);
}
if (op1 == '*') {
printf("%f \n", val1 * val2);
}
if (op1 == '/') {
printf("%f \n", val1 / val2);
}
}
else if (op == 2) {
double arg;
printf("Please type the argument of sin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", sin(arg));
}
else if (op == 3) {
double arg;
printf("Please type the argument of cos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", cos(arg));
}
else if (op == 4) {
double arg;
printf("Please type the argument of tan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", tan(arg));
}
else if (op == 5) {
double arg;
printf("Please type the argument of arcsin(x) \n");
scanf("%lf", &arg);
printf("The value is %f", asin(arg));
}
else if (op == 6) {
double arg;
printf("Please type the argument of arccos(x) \n");
scanf("%lf", &arg);
printf("The value is %f", acos(arg));
}
else if (op == 7) {
double arg;
printf("Please type the argument of arctan(x) \n");
scanf("%lf", &arg);
printf("The value is %f", atan(arg));
}
else {
printf("%d", 0);
}
}
}
Sorry for too many to read:((( Im not experienced with forums.
The following example will give you an idea how things can be repeated based on input.
check how strcmp is done,that way you are doing is wrong.
Also consider using switch for handling multiple cases of input and their operations.
#include<stdio.h>
#include <string.h>
#include <ctype.h> // isspace
int main() {
char choice[] = "Yes";
do{
int i = 0;
/**
* implement all you want here
*/
printf("Enter Yes to repeat, to exit enter any other non blank string\n");
while(isspace(choice[i] = getchar()));
while((choice[++i] = getchar()) != '\n');
choice[i] = '\0';
printf("choice = %s, i = %d\n", choice, i);
}while(!strcmp(choice,"Yes") );
return 0;
}

Getting one loop for multiple characters using "while"

I'm new on Stackoverflow and I'm very, completely new to coding. Just messing around with C. Here's what I'm trying to do here (don't take this program scientifically accurate), this is a program that calculates for special relativity equations of length, mass and time. I have 3 questions actually:
When I try to put other characters in the y/n questions, everything works but for example if I enter "sfkl", the warning comes up 4 times because I entered 4 characters. And if I put space, it doesn't even give a warning until I put another character and then enter. Can I make it give 1 warning no matter how many characters I enter in one line (including space)?
My other question is, I kind of prevented inputting anything other than y/n but for the double value inputs (mass, length and time), I can't figure out a similar system (asking for a double value over and over again). Can you suggest me a solution?
And my third question is, when doing "scanf_s(" %c", &answer);", if I don't put a space before "%c", it doesn't work properly. It registers an enter and asks me to enter y/n only. Why need a space before that?
Here's the code:
#include <stdio.h>
#include <math.h>
#define LIGHT 299792458
int input();
int main()
{
printf("\n\n\tThis program calculates how length, mass and time changes with respect to your speed.\n\n\tThe values you enter are the quantites which are observed by a stationary observer and the output values are the quantites observed by the person in a vehicle which is moving at the speed that you enter.");
input();
return 0;
}
int input()
{
double length, mass, utime, speed;
char answer;
do
{
printf("\n\n **************************************************");
printf("\n\n\tPlease enter a quantity of length: ");
scanf_s("%lf", &length);
printf("\n\tPlease enter a quantity of mass: ");
scanf_s("%lf", &mass);
printf("\n\tPlease enter a quantity of time: ");
scanf_s("%lf", &utime);
printf("\n\tNow enter the speed of the vehicle (m/s): ");
scanf_s("%lf", &speed);
while (speed > LIGHT)
{
printf("\n\n\tNothing can surpass the speed of light in the universe. Enter a smaller value: ");
scanf_s("%lf", &speed);
}
double newlength = length * (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
double newmass = mass / (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
double newutime = utime / (sqrt(1 - pow(speed, 2) / pow(LIGHT, 2)));
if (speed == LIGHT)
{
printf("\n\n **************************************************");
printf("\n\n\n\tIt's technically impossible to reach the speed of light if you have mass but here are the mathematical limit results:\n\n\t*The new length quantity is 0\n\n\t*The new mass quantity is infinity\n\n\t*The new time quantity is infinity\n\n\n\t- Time successfully dilated -\n\n");
printf("\n\tDo you want to start over? (y/n): ");
scanf_s(" %c", &answer);
if (answer == 'n')
{
return 0;
}
else if (answer == 'y')
{
continue;
}
else
{
while (answer != 'y' && answer != 'n')
{
printf("\n\tPlease only enter 'y' or 'n': ");
scanf_s(" %c", &answer);
}
}
}
if (speed < LIGHT)
{
printf("\n\n **************************************************");
printf("\n\n\n\t*The new length quantity is %.20lf\n\n\t*The new mass quantity is %.20lf\n\n\t*The new time quantity is %.20lf\n\n\n\t- Time successfully dilated -\n\n", newlength, newmass, newutime);
printf("\n\tDo you want to start over? (y/n): ");
scanf_s(" %c", &answer);
if (answer == 'n')
{
return 0;
}
else if (answer == 'y')
{
continue;
}
else
{
while (answer != 'y' && answer != 'n')
{
printf("\n\tPlease only enter 'y' or 'n': ");
scanf_s(" %c", &answer);
}
}
}
}
while (answer == 'y');
return 0;
}
Thank you, have a good day
The return value of scanf is the number of elements parsed successfully; you can use this to repeat until something has been read successfully:
double nr=0;
while (!feof(stdin) && scanf("%lf",&nr)!=1) {
printf("not a number; try again.");
while ( (c = getchar()) != '\n' && c != EOF ) { }
}
Note that you have to take "invalid" input out of the buffer; otherwise, scanf would fail again and again.

How can i make the user choose the unit

I have a converter, but it converts all the units that are in the program.how can i make that the user who opens the project to choose what type of unit to convert?
#include<stdio.h>
#include<conio.h>
int main()
{
float m, f, l, g, cm, inch;
printf("Type meter : ");
scanf("%f",&m);
f = 3.2808399 * m;
printf("feets: %f",f);
printf("\nType gallons : ");
scanf("%f",&g);
l = 3.78541178 * g;
printf("litres: %f",l);
printf("\ninches : ");
scanf("%f", &inch);
cm = 2.54 * inch;
printf("cm: %f", cm);
return 0;
}
This code below is definitely not the best one in terms of complexity, portability, optimisation (Memory/Time) and many other aspects of programming, but it should get you going.
I have added comments to explain the code. Almost all of the code with all those printfs is self-explanatory.
#include<stdio.h>
int main(void)
{
// We need just 3 variables
// This one is for getting the user option
int choice = 0;
// We need these to float variables for user input and an output
float Input = 0.0, Output = 0.0;
// Following code till `while(1)` is optional.
printf("\nThis is a converter with a fixed set of functions.");
printf("\nNote: This converter does support floating point inputs.");
printf("\nNote: Floating point inputs and outputs are truncated to 2 digits after decimal place.");
printf("\nNote: Press any key to acknowledge!");
getchar();
// To get user input multiple times, you'll need to loop
while(1)
{
printf("\n\nFollowing functions are supported, enter a suitable choice form the list below.");
printf("\nPress `1` for Converting Metres to Feet.");
printf("\nPress `2` for Converting Gallons to Litres.");
printf("\nPress `3` for Converting Inches to Centimetres.");
printf("\nPress `0` for Exiting the program.");
printf("\nEnter your Option : ");
scanf("%d", &choice);
// Lets implement a switch-case statement to get the job done
switch(choice)
{
case 1:
printf("Enter input value (in Metres) : ");
scanf("%f",&Input);
Output = 3.2808399 * Input;
printf("%0.2f Metres is equal to %0.2f Feets", Input, Output);
break;
case 2:
printf("Enter input value (in Gallons) : ");
scanf("%f",&Input);
Output = 3.78541178 * Input;
printf("%0.2f Gallons is equal to %0.2f Litres", Input, Output);
break;
case 3:
printf("Enter input value (in Inches) : ");
scanf("%f",&Input);
Output = 2.54 * Input;
printf("%0.2f Inches is equal to %0.2f Centimetres", Input, Output);
break;
case 0:
printf("Thank you. The program will exit now!\n\n");
return 0;
break;
// This default case should take care of the invalid set of choices entered by user
default:
printf("Option you entered is either invalid or is not supported as of now!");
}
}
return 0;
}
Another way to implement this could be using an if-else if-else ladder.
So you can remove swtich-case statements from the code below and replace it with the following:
if(choice == 0)
{
printf("Thank you. The program will exit now!\n\n");
return 0;
}
else if(choice == 1)
{
printf("Enter input value (in Metres) : ");
scanf("%f",&Input);
Output = 3.2808399 * Input;
printf("%0.2f Metres is equal to %0.2f Feets", Input, Output);
}
else if(choice == 2)
{
printf("Enter input value (in Gallons) : ");
scanf("%f",&Input);
Output = 3.78541178 * Input;
printf("%0.2f Gallons is equal to %0.2f Litres", Input, Output);
}
else if(choice == 3)
{
printf("Enter input value (in Inches) : ");
scanf("%f",&Input);
Output = 2.54 * Input;
printf("%0.2f Inches is equal to %0.2f Centimetres", Input, Output);
}
else
{
// This should take care of the invalid set of choices entered by user
printf("Option you entered is either invalid or is not supported as of now!");
}
char unit;
printf("Which unit do you want to convert (input:m,g,i): ");
scanf("%c",&unit);
if(unit == 'm') ...
else if( if(unit == 'g'))....
else if( if(unit == 'i'))....
else printf("wrong input ! \n");

How do I only accept numbers in C and block the user from entering letters and special characters?

I just need to figure out how to give an error is the user enters anything that is not number. I already set the values of the code that cannot be passed or be gone under.
I just need to only accept numbers: if a letter or any type of special character is entered I want the program to just cancel itself. How can I do this?
#include <stdio.h>
#include <math.h>
int main(void) {
float base, height;
float area;
printf("Please enter the value of base of the triangle: \n");
scanf ("%f", &base);
if(base<.5)
printf("Invalid Input\n");
while (base<.5)
return 0;
if(base>100)
printf("Invalid Input\n");
while(base>100)
return 0;
printf("Please enter the value of height of the triangle:\n");
scanf("%f", &height);
if(height<1)
printf("Invalid Input\n");
while(height<1)
return 0;
if(height>75)
printf("Invalid Input\n");
while (height>75)
return 0;
area = base * height/2;
printf("The area of the triangle for base: %f and height: %f is %f \n", base,
height , area );
return 0;
}
You cannot block the user from entering whatever he or she wants, but you can use the return value of scanf to decide if a valid value has been entered, and prompt the user for a correct input:
float base;
do {
printf("Please enter the value of base of the triangle: \n");
} while (scanf ("%f", &base) != 1 || base < .5 || base > 100);
This loop will continue until all three conditions are met:
scanf has returned exactly one item,
The value provided by scanf is greater than or equal to 0.5, and
The value provided by scanf is less than or equal to 100
scanf returns the number of variables that have been matched and filled with values succesfully.
just do:
int result = scanf ("%f", &base);
if(result != 1)
{
...//handle error
}
I think that you could read the input character by character and then check if it's a number and if it isn't you show your error message.
#include <stdio.h>
#include <math.h>
int main(void)
{
float base, height;
float area;
printf("Please enter the value of base of the triangle: \n");
char c='\n';
char success=0;
base=0;
char dot=0;
do{
scanf ("%c", &c);
if((c>=48)&&(c<=57)){
if(dot==0)
base=base*10+(c-48);
else{
base+=(c-48)/dot;
dot*=10;
}
}
else
if((c=='.')&&(dot==0))
dot=10;
else
if(c!='\n')
success=1;
}while((c!='\n')&&(succes==0));
if(success!=0) return -1; //error we break out
if(base<.5)
printf("Invalid Input\n");
while (base<.5)
return 0;
if(base>100)
printf("Invalid Input\n");
while(base>100)
return 0;
printf("Please enter the value of height of the triangle:\n");
c='\n';
success=0;
height=0;
dot=0;
do{
scanf ("%c", &c);
if((c>=48)&&(c<=57)){
if(dot==0)
height=height*10+(c-48);
else{
height+=(c-48)/dot;
dot*=10;
}
}
else
if((c=='.')&&(dot==0))//check if is the first time the user insert a dot
dot=10;
else
if(c!='\n')
success=1;
}while((c!='\n')&&(succes==0));
if(success!=0) return -1; //error we break out
if(height<1)
printf("Invalid Input\n");
while(height<1)
return 0;
if(height>75)
printf("Invalid Input\n");
while (height>75)
return 0;
area = base * height/2;
printf("The area of the triangle for base: %f and height: %f is %f \n", base,
height , area );
return 0;
}

Resources