How can i make the user choose the unit - c

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");

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;
}
}

Simple IF statement scanf

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.

C program to make a calculator that can perform simple arithmetic and toggle between int and double variables

I am a bit new to c programming. For my project I have been tasked with developing a simple calculator that asks the user to input an option then that option declares what operation is to be performed (i.e. if the user enters 1, this corresponds to selecting the addition option which then allows the user to add two numbers they choose. I have the majority of the code worked out, but the catch is that I need the calculator to toggle between int and double variables. When the user enters 5, the calculator should now work with integers then if the user hits 5 again, the calculator switches back to doubles and vice versa so long as you want to switch back and forth. The calculator automatically works with doubles. So, more specifically, if I wanted to use integer variables, I would enter 5, then lets say I wanted to switch back to doubles, I should enter five and receive the message "Calculator now works with doubles." So here is my code thus far:
#include<stdio.h>
#include<math.h>
#include<stdbool.h>
int main()
{
int integermode, doublemode, m, a, b, sum2, difference2, product2,
quotient2;
double i, j, sum1, difference1, product1, quotient1;
printf("This program implements a calculator.");
while(m !=6) {
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%d", &m);
if(m > 6) {
printf("Invalid option.\n");
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%d", &m);
}
switch (m) {
case 1:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The sum is: %d\n", a+b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The sum is: %.15lf\n", i+j);
}
break;
case 2:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The difference is: %d\n", a-b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The difference is: %.15lf\n", i-j);
}
break;
case 3:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
printf("The product is: %d\n", a*b);
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
printf("The product is: %.15lf\n", i*j);
}
break;
case 4:
if (integermode == true) {
printf("Enter first term: ");
scanf("%d", &a);
printf("Enter second term: ");
scanf("%d", &b);
if (b != 0) printf("The quotient is: %d\n", a/b);
if (b == 0) printf("Cannot divide by zero!\n");
break;
}
if (integermode == false) {
printf("Enter first term: ");
scanf("%lf", &i);
printf("Enter second term: ");
scanf("%lf", &j);
if(j != 0) printf("The quotient is: %.15lf\n", i/j);
if(j == 0) printf("Cannot divide by zero!\n");
break;
}
case 5:
if (m = 5) {
integermode = true;
printf("Calculator now works with integers.\n");
}
if (m != 5) integermode = false;
}
}
return 0;
}
General improvements
First off, you should notice your main function is massive for what it needs to accomplish, and takes a ton of indent levels (when properly indented). That is mostly because you've got a ton of duplicated functionality. You could easily extract the code that asks for the input numbers into a function and reuse it, changing only the operation performed in each case. Or probably even better, you could ask for the input numbers as a part of the main while loop, and then perform a different operation with them depending on the operation mode you're in.
You're not using <math.h>, so you can leave it out.
Another thing I've noticed is you don't initialize the m variable before using it in the while loop. That could potentially cause a lot of problems, so you should initialize it to some value that isn't a valid mode, like for example 0 or -1.
You're also using two consecutive if statements when if/else could be used.
if (integermode == true) {
.....
}
if (integermode == false) {
.....
}
is the same as
if (integermode == true) {
.....
} else {
.....
}
but harder to read and less efficient, as you're doing two comparisons instead of one.
Implementation of double/integer modes
About the functionality you want to implement, you could very well define an enumeration with the possible modes:
typedef enum _datamode {
INTEGER_MODE,
DOUBLE_MODE
} data_mode;
and then have a variable holding the current mode:
data_mode datamode = INTEGER_MODE /* Initializing this to the default mode */
then use integers or doubles during the calculation and output depending on the current value of the variable. Of course, this could be done in a shorter way with an integer instead of an enum and a typedef, but I find this to be a more verbose way.
For the inputs and the result, you could use the union C type, which reserves memory for the biggest type you specify inside it and lets you store any of them in it. For example:
union io {
int i;
double d;
} a, b, result;
declares three variables that have the io union as type. That way, you can use them as integers or doubles as you like (as long as you don't mix types up and, for example, store an integer and read it as a double)
Full working implementation
The following would be my implementation of the program you have to do. It could be accomplished in a much shorter way (take into account the switches dealing with enums take a fair bit of the total space) but I think this is way more elegant and verbose.
I've respected your print statements and the flow of your application, even though I think they could be better (maybe this is something your assignment imposes on you?)
Please take this as an opportunity to learn and don't just copy-paste the code.
#include <stdio.h>
#include <stdlib.h>
typedef enum _datamode {
INTEGER_MODE,
DOUBLE_MODE
} data_mode;
typedef enum _operationmode {
ADDITION,
SUBSTRACTION,
MULTIPLICATION,
DIVISION,
TOGGLE,
EXIT
} operation_mode;
operation_mode ask_mode () {
int input = -1;
while (1) {
printf("Options:\n");
printf("1 - addition\n2 - subtraction\n3 - multiplication\n4 - division\n5 - toggle calculator type\n6 - exit program\n");
printf("Please enter your option: ");
scanf("%i", &input);
if (input < 1 || input > 6) {
printf("Invalid option.\n");
} else {
switch (input) {
case 1:
return ADDITION;
case 2:
return SUBSTRACTION;
case 3:
return MULTIPLICATION;
case 4:
return DIVISION;
case 5:
return TOGGLE;
case 6:
return EXIT;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
}
}
}
union _io {
int i;
double d;
};
void get_inputs_integer (int *a, int *b) {
printf("Enter first term: ");
scanf("%i", a);
printf("Enter second term: ");
scanf("%i", b);
}
void get_inputs_double (double *a, double *b) {
printf("Enter first term: ");
scanf("%lf", a);
printf("Enter second term: ");
scanf("%lf", b);
}
int main (int argc, char **argv) {
union _io operand1, operand2, result;
operation_mode o_mode;
data_mode d_mode = INTEGER_MODE;
printf("This program implements a calculator.");
do {
o_mode = ask_mode();
if (o_mode == TOGGLE) {
if (d_mode == INTEGER_MODE) {
d_mode = DOUBLE_MODE;
printf("Calculator now on double mode\n");
} else {
d_mode = INTEGER_MODE;
printf("Calculator now on integer mode\n");
}
} else if (o_mode != EXIT) {
if (d_mode == INTEGER_MODE) {
get_inputs_integer(&operand1.i, &operand2.i);
switch (o_mode) {
case ADDITION:
result.i = operand1.i + operand2.i;
break;
case SUBSTRACTION:
result.i = operand1.i - operand2.i;
break;
case MULTIPLICATION:
result.i = operand1.i * operand2.i;
break;
case DIVISION:
result.i = operand1.i / operand2.i;
break;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
printf("The result is %i\n", result.i);
} else {
get_inputs_double(&operand1.d, &operand2.d);
switch (o_mode) {
case ADDITION:
result.d = operand1.d + operand2.d;
break;
case SUBSTRACTION:
result.d = operand1.d - operand2.d;
break;
case MULTIPLICATION:
result.d = operand1.d * operand2.d;
break;
case DIVISION:
result.d = operand1.d / operand2.d;
break;
default:
exit(EXIT_FAILURE); /* Error must've occurred in order for a different value to be present */
}
printf("The result is %lf\n", result.d);
}
}
} while (o_mode != EXIT);
}

How to make this program ask for input again if invalid input is entered (in C programming)? [duplicate]

This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 5 years ago.
There are two different spots where the check happens.
That is, where you enter a, s, m, d, or q and when you enter the first and second number.
At any of the checks, if the check is false, it should ask you to re-enter your input.
I'm guessing this can be done by putting a scanf statement for the numbers part inside a while loop check, but when I enter an invalid value (non-number) the loop runs infinitely.
So I must be doing something wrong. I have made the a, s, m, d, and q part work for the most part.
But the second part never seems to work. For this, I left my failed attempts at the while loops out, and instead in //comments.
Any help would be greatly appreciated!
Here is my code so far:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
float num1,num2,answer;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
while ((ch = getchar())!='q')
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
ch=tolower(ch);
if (ch=='\n')
continue;
else
{
switch(ch)
{
case 'a':
//The code below is what I have tried to make work.
//This code would also be copy pasted to the other cases,
//of course with the correct operations respectively being used.
//
//printf("Enter first number: ")
//while(scanf("%f",&num1)==0)
//{
// printf("Invalid input. Please enter a number.");
// scanf("%f",&num1);
//}
//printf("Enter second number: ")
//while(scanf("%f",&num2)==0)
//{
// printf("Invalid input. Please enter a number.");
// scanf("%f",&num2);
//}
//answer = num1 + num2;
//printf("%f + %f = %f\n",num1,num2,answer);
//break;
//
//I have also tried to make this work using do-while loops
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 + num2;
printf("%f + %f = %f\n",num1,num2,answer);
break;
case 's':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 - num2;
printf("%f - %f = %f\n",num1,num2,answer);
break;
case 'm':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 * num2;
printf("%f * %f = %f\n",num1,num2,answer);
break;
case 'd':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 / num2;
printf("%f / %f = %f\n",num1,num2,answer);
break;
default:
printf("That is not a valid operation.\n");
break;
}
}
}
return 0;
}
Again, thanks for any help!
Ya'll would be a life saver!
Cheers!
-Will S.
EDIT: I got my code to work! Here is the final code...
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
float num1,num2,answer;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
while ((ch = getchar())!='q')
{
ch=tolower(ch);
//Ignore whitespace
if (ch=='\n')
continue;
else
{
switch(ch)
{
//Addition part
case 'a':
//First number
printf("Enter first number: ");
//Check to see if input is a number
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Second number
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Do math for respective operation
answer = num1 + num2;
//Print out result
printf("%.3f + %.3f = %.3f\n", num1,num2,answer);
break;
//Subtraction part
case 's':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
answer = num1 - num2;
printf("%.3f - %.3f = %.3f\n", num1,num2,answer);
break;
//Multiplication part
case 'm':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
answer = num1 * num2;
printf("%.3f * %.3f = %.3f\n", num1,num2,answer);
break;
//Division part
case 'd':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Check for if number is a zero
while (num2==0)
{
printf("Please enter a non-zero number, such as 2.5, -1.78E8, or 3: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
}
answer = num1 / num2;
printf("%.3f / %.3f = %.3f\n", num1,num2,answer);
break;
//For if a non-valid operation is entered
default:
printf("That is not a valid operation.\n");
break;
}
}
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
}
printf("Bye.\n");
return 0;
}
Looking back at it, I probably could do without the if/else statement.
There are multiple problems with your code. First of all in this loop
You are taking input two times on failure
while(scanf("%f",&num1)==0) //Taking Input Here Once
{
printf("Invalid input. Please enter a number.");
scanf("%f",&num1); //Again Taking input.
}
Instead what you wanted was to check the return value of the scanf() and if it was 0 you would execute the loop again, so this would be the way to do that:
int l = 0;
while(l==0){ //Checking l, if it is zero or not, if zero running loop again.
printf("Invalid input. Please enter a number.");
l = scanf("%f",&num1); //Storing Return Value of scanf in l
}
When the program will encounter any line with scanf("%f" , &num1) or scanf("%f" , &num2), it will skip all the white spaces and wait for next input. In the case where the input does not match the format specification, then the input isn't consumed and remains in the input buffer.
int l = 0;
while(l==0){ //Checking l
printf("Invalid input. Please enter a number.");
l = scanf("%f",&num1); //scanf will look at the buffer if the input
//does not match, it will not be consumed
//and will remain in buffer.
}
In other words, the character that doesn't match is never read. So when you type e.g. an a character, your code will loop indefinitely as scanf continues to fail on the same character.
When the program executes its last scanf("%f",&num2) call then because of the enter there is a newline \n character present in buffer and so due to ch = getchar(), new line \n gets stored in ch and the following if condition satisfies and the loop execute again.
if(ch =='\n')
continue;
while(scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number.");
scanf("%f",&num1);
}
This loops scans two numbers per iteration. This is not what you want. Lose the second scanf.
You should also check for EOF and errors.
int result;
while((result = scanf("%f",&num1))==0)
{
printf("Invalid input. Please enter a number.");
}
if (result == EOF) .... report an error and exit ...

How to make getchar() read a negative number?

I am writing a program that can calculate the areas of a square, cube, and circle. The program needs to present an error message and allow the user to enter a new choice if they enter something not included in the menu. My problem is that if they type anything includes my menu options then the program still executes. (i.e. -1, 23, 344) I was wondering how to get it to ignore anything after the first character or to read the whole string. Or if there is something better than getchar(). I'm open to any solutions! Thank you!
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int choice;
int lengthsq;
int areasq;
int lengthcube;
int areacube;
int radius;
double circlearea;
printf("Area Calculation\n");
printf("(1) Square\n");
printf("(2) Cube\n");
printf("(3) Circle\n");
fputs("Please make a selction: ", stdout);
while((choice = getchar()) != '\n')
switch (choice) {
case '1':
printf("\nPlease enter the length: ");
scanf("%d", &lengthsq);
while(lengthsq <= 0){
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthsq);
}
areasq = lengthsq * lengthsq;
printf("The area of the square is %d.", areasq);
return 0;
case '2':
printf("\nPlease enter the length: ");
scanf("%d", &lengthcube);
while (lengthcube <= 0) {
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthcube);
}
areacube = 6 * lengthcube * lengthcube;
printf("The surface area of the cube is %d.\n", areacube);
return 0;
case '3':
printf("\nPlease enter the radius: ");
scanf("%d", &radius);
while(radius <= 0){
printf("Error! Pleae enter a postive number: ");
scanf("%d", &radius);
}
circlearea = 3.14159 * radius * radius;
printf("The area of the circle is %.2f.\n", circlearea);
return 0;
case '\n':
case '\t':
case ' ':
break;
default:
printf("\nInvalid choice entered.\n");
fputs("Enter a new choice: ", stdout);
break;
}
}
You could add another switch case for the dash, which would toggle some kind of negative flag and then read a number as you're already doing. If you do not like introducing such a flag, then the best option would be using fgets, which returns the entire input line. But that has the downside that you need to parse the input. I.e. do some string manipulation, which may be slightly more complex than a simple flag parameter.
On the other hand, from the code you attached, I deduct that the only valid input consists of mere numbers (integers). You could just read an integer then with scanf.

Resources