Calculator program requires + and - to be entered twice - c

I am writing a simple calculator program to add, subtract, multiply, divide and do exponential equations. The program must repeat until "q0" is entered and it must have two functions called by the main function like I have written. The problem is when I run the program the first number shows up fine and then I can multiply, divide, and do exponential functions fine but if I want to add or subtract I must enter the + or - twice for it to count it. This is the program I have written:
#include <stdio.h>
#include <math.h>
void scan_data(char *oprter, double *oprand);
void do_next_op(char oprter, double oprand, double *accum);
int
main(void)
{
double nmber, /* input/output - operand */
total; /* output - final result */
char sign; /* input/output - operator */
total = 0;
do {
scan_data(&sign, &nmber);
do_next_op(sign, nmber, &total);
} while (sign != 'q');
printf("Final result is %.2f", total);
return (0);
}
/*
* Gathers operator and operand to perform calculation
* Post: results are stored in cells pointed to by oprter, and oprand
*/
void
scan_data(char *oprter, /* input - amount being withdrawn */
double *oprand) /* output - number of tens */
{
double amount;
amount = 0;
scanf("%c", &*oprter);
scanf("%lf", &amount);
*oprand = amount;
}
/*
* Performs calculation and displays results
* Pre: oprter and oprand are defined
* Post: function results are stored in cell pointed to by accum
*/
void
do_next_op(char oprter,
double oprand,
double *accum)
{
double tot_amount;
tot_amount = *accum;
switch(oprter)
{
case '+':
tot_amount = (tot_amount + oprand);
printf("result so far is %.2f\n", tot_amount);
break;
case '-':
tot_amount = (tot_amount - oprand);
printf("result so far is %.2f\n", tot_amount);
break;
case '*':
tot_amount = tot_amount * oprand;
printf("result so far is %.2f\n", tot_amount);
break;
case '/':
tot_amount = tot_amount / oprand;
printf("result so far is %.2f\n", tot_amount);
break;
case '^':
tot_amount = pow(tot_amount, oprand);
printf("result so far is %.2f\n", tot_amount);
break;
}
*accum = tot_amount;
}
An example of what it is doing follows:
+5
result so far is 5.00
+5
-5
++5
result so far is 10.00
--5
result so far is 5.00
*2
result so far is 10.00
/2
result so far is 5.00
^2
result so far is 25.00
q0
Final result is 25.00

The problem is most likely that scanf leaves the newline in the input buffer when you do
scanf("%lf", &amount);
That means that the next call to
scanf("%c", oprter);
it will read that newline.
This can be solved by asking scanf to read and skip all leading whitespace by adding a single space to the scanf format string like
scanf(" %c", oprter);
// ^
// |
// Note space here

Related

Builidng a calculator in c language can use a previous result

i got problem with this calculator which i need to use the previous result of previous operartion (if i want to ) but when i do it it gives correct if only give it the same previous operation
here is the code :
#include<stdio.h>
#include<math.h>
double addition (double a, double b)
{
double add;
add=a+b;
return add;
}
double soustraction (double a, double b)
{
double sous;
sous=a-b;
return sous;
}
double multiplication (double a,double b)
{
double multi;
multi=a*b;
return multi;
}
double division (double a, double b)
{
double div;
div=a/b;
return div;
}
double reste_de_division (int a,int b)
{
double rest;
rest=a%b;
return rest;
}
double puissance( double a,double b)
{
int i;
double r;
i = 0;
r = 1;
while (i < b){
r = r * a;
i ++;
}
return r;
}
double factorielle (double a)
{
int i;
double facto;
facto=1;
for(i=0;i<a;i++)
{facto=(a-i)*facto;
}
return facto;
}
double PGCD (int a,int b)
{
int i;
double pgcd;
for(i=1; i <= a && i <= b; ++i)
{
if(a%i==0 && b%i==0)
pgcd = i;
}
return pgcd;
}
double PPCM (int a,int b)
{
int ppcm;
ppcm = (a > b) ? a : b;
while(ppcm%a !=0 || ppcm%b !=0)
ppcm=ppcm+1;
return ppcm;
}
double inverse (double a)
{
double inv;
inv=1/a;
return inv;
}
int main(){
double a,b,r;
char ch;
printf("\n***************************************\n");
printf (" \n + Addition \t \t - Subtraction \n * Multiplication \t / Division \n Reste de division \t c Puissance \n ! Factorielle \t \t g PGCD \n p PPCM \t \t i Inverse \n q Quitter \n");
printf("\n***************************************\n");
printf("Donner les deux nombres et l'operation:\n");
do
{b=r;
scanf("%lf %lf %c",&a,&b,&ch);
switch (ch)
{case '+':
r=addition(a,b);
printf("%lf\n",r);
break;
case '-':
r=soustraction(a,b);
printf("%lf\n",r);
break;
case '*':
r=multiplication(a,b);
printf("%lf\n",r);
break;
case '/':
r=division(a,b);
printf("%lf\n",r);
break;
case '%':
printf("%lf\n",reste_de_division(a,b));
break;
case 'c':
printf("%lf\n",puissance(a,b));
break;
case '!':
printf("%lf\n",factorielle(a));
break;
case 'g':
printf("%lf\n",PGCD(a,b));
break;
case 'p':
printf("%lf\n",PPCM(a,b));
break;
case 'i':
printf("%lf\n",inverse(a));
break;
}
}while(ch !='q');
return 0;
}
Sorry for my bad english
example:
5 6 +
11
6 +
17
3 -
20 //this is error, it's supposed to give 14 not 20
Your problem is here:
scanf("%lf %lf %c",&a,&b,&ch);
You expect the user to always input two doubles and one character. If the user only gives one double and one character, the value of ch (and b) is unchanged and the program will do the same operation as it did the last time.
Example:
First input:
5 6 +
This will make a equal 6, b equal 5 and ch equal +. Consequently the program will add the two numbers 5 and 6 and produce the result 11 which is stored in b.
Next input:
1 -
This will make a equal one but leave both b and ch unchanged, i.e. b is still equal 11 and ch is still equal +. Consequently the program will add the two numbers 1 and 11 and produce the result 12 which is stored in b.
This is just one example of things that can go wrong when doing scanf("%lf %lf %c",&a,&b,&ch); There are other input sequences that will lead to (even more) bizar output.
You need a much more strict parsing of user input. The scanf functions isn't good for that. Consider using fgets to read a whole line and the parse it afterwards. With care that can be done using sscanf.

Why won't my result update after the first iteration(?)

#include <stdio.h>
#include <math.h>
void scan_data(char *op, float *operand);
float do_next_op(char op, float operand, float *accumulator);
int main(void)
{
char op;
float operand;
float accumulator = 0;
do
{
printf(" + add\n - subtract\n * multiply\n / divide\n ^ power\n q quit\n\n");
scan_data(&op, &operand);
if(op == 'q' || op == 'Q')
{
printf("Final result is %.1f\n", do_next_op(op, operand, &accumulator));
break;
}
else
{
printf("result so far is %.1f\n", do_next_op(op, operand, &accumulator));
}
}while(op != 'q' || op == 'Q');
}
void scan_data(char *op, float *operand)
{
scanf("%c%f",op, operand);
}
float do_next_op(char op, float operand, float *accumulator)
{
switch(op)
{
case('+'):
*accumulator = *accumulator + operand;
break;
case('-'):
*accumulator = *accumulator - operand;
break;
case('*'):
*accumulator = *accumulator * operand;
break;
case('/'):
*accumulator = *accumulator / operand;
break;
case('^'):
*accumulator = pow(*accumulator,operand);
break;
}
return *accumulator;
}
I'm trying to code a "simple" calculator where if i type
+5.0
result so far is 5.0
^2
result so far is 25.0
/ 2.0
result so far is 12.5
Q 0
final result is 12.5
The problem is, the code will "correctly" output the first operation but if i put anymore operation after that I doesn't update to the new value.
How can I fix the code to do what I intend to do?
I'm sorry in advance if my question wording and format is off, I don't know how to ask it in a proper way.
the problem is in the statement:
scanf("%c%f",op, operand);
After the first iteration, there is a left over newline in stdin
That newline is a 'white space', typically \n
That 'white space must be consumed before the %c rather than the %c consuming it. Suggest:
scanf(" %c%f",op, operand);
where the leading space in the format string consumes that 'white space'
regarding the statement:
*accumulator = pow(*accumulator,operand);
the pow() function expects to be working with double values, not float values. Suggest:
*accumulator = powf(*accumulator,operand);
Notice this is calling powf() not pow()

Using switch statements to call functions

I'm trying to write a program in C that uses switch statements to decide which called function to use to convert various values. My instructions were as follows:
"Create a program to convert Fahrenheit to Celsius, Celsius to Fahrenheit, inches to centimeter, and centimeters to inches. Put your choices into a switch statement so they will appear on the screen like below:
Select from the menu below to covert temperature or linear menus:
1 Convert Fahrenheit to Celsius
2 Convert Celsius to Fahrenheit
3 Convert Inches to Centimes
4 Convert Centimeters to Inches
5 Exit the program
Enter your selection:
ake each of the conversion routines a function that you will call from the main program. Each of the selections should be a case in a switch statement. Be sure to comment all your code according to the coding standards.
When I run the program and enter the choice followed by the value to convert, a weird number shows up followed by
ProgramExiting.ProgramExiting.
Here is my code:
#include <stdio.h>
void FahrenheitToCelsiusConversion (double conversionValue) {
double output;
output = conversionValue / (9.0 / 5.0) - 32;
printf("%d", output);
}
void CelsiusToFahrenheitConversion (double conversionValue) {
double output;
output = conversionValue * (9.0 / 5.0) + 32;
printf("%d", output);
}
void InchesToCentimetersConversion (double conversionValue) {
double output;
output = conversionValue * 2.54;
printf("%d", output);
}
void CentimetersToInchesConversion (double conversionValue) {
double output;
output = conversionValue / 2.54;
printf("%d", output);
}
int main(void) {
int conversionChoice;
double conversionValue;
printf("Select from the menu below to convert temperature or linear\n");
printf("menus:");
printf("\n");
printf("1 Convert Fahrenheit to Celsius\n");
printf("2 Convert Celsius to Fahrenheit\n");
printf("3 Convert Inches to Centimeters\n");
printf("4 Convert Centimeters to Inches\n");
printf("5 Exit the Program\n");
scanf("%d", &conversionChoice);
printf("Enter the value you wish to convert:\n");
scanf("%d", &conversionValue);
switch (conversionChoice) {
case 1:
FahrenheitToCelsiusConversion(conversionValue);
case 2:
CelsiusToFahrenheitConversion(conversionValue);
case 3:
InchesToCentimetersConversion(conversionValue);
case 4:
CentimetersToInchesConversion(conversionValue);
case 5:
printf("Program exiting.");
default:
printf("Program exiting.");
}
return 0;
}
You are missing breaks for a start. (so if you pick option 1 it will also perform options 2 3 4 and 5)
conversionValue is a double but you scan it in with %d. This means you aren't converting the value you think you are. Basic debug (printing your input values) would highlight that.
All your prints are trying to print a double with %d (should be %lf for doubles)
Combining output with calculations is bad. i.e. Your convert routines should return the converted value and the print should be outside the convert function.
As a follow on to your comments, understand that printf will print doubles using "%f" by default, however, to read a double with scanf you must use the l length-modifier, e.g. "%lf". A mismatch in format specifiers results in Undefined Behavior.
Further, as you found, your F->C conversion logic needs... help. The 32 is being subtracted at the wrong point, it should be:
void FahrenheitToCelsiusConversion (double conversionValue) {
double output;
output = (conversionValue - 32) / (9.0 / 5.0);
printf ("%.2f\n", output);
}
(note: the printf format change as well)
Further, in main() you need only a single call to printf (or fputs since no conversions are involved) to print the entire menu. When you terminate a line with a double-quote and the next begins with a double-quote, C will concatenate the strings, e.g.
printf ("\nSelect from the menu below to convert temperature or linear\n"
"menus:\n\n"
" 1 Convert Fahrenheit to Celsius\n"
" 2 Convert Celsius to Fahrenheit\n"
" 3 Convert Inches to Centimeters\n"
" 4 Convert Centimeters to Inches\n"
" 5 Exit the Program\n\n"
"choice: ");
Always, always validate all User Input, this means at minimum validating the return of scanf (and if not exiting after a matching failure -- you must read and discard all offending characters that remain in stdin because when a matching failure occurs, no further characters are removed from the input buffer and any offending characters that caused the matching failure remain unread just waiting to bite you again on your next attempt to read from the input buffer).
At minimum check that the number of conversions expected completed successfully (and you should further check that any numeric input is within range, if applicable), e.g.
if (scanf ("%d", &conversionChoice) != 1 || conversionChoice < 1 ||
conversionChoice > 5) {
fputs ("error: invalid input, or value out of range.\n", stderr);
return 1;
}
printf ("\nEnter the value you wish to convert: ");
if (scanf ("%lf", &conversionValue) != 1) {
fputs ("error: invalid value input.\n", stderr);
return 1;
}
You indicate you have added break statements to your switch statement, but after our discussion of the default fall-through behavior, do you understand why the following works?
switch (conversionChoice) {
case 1:
FahrenheitToCelsiusConversion(conversionValue);
break;
case 2:
CelsiusToFahrenheitConversion(conversionValue);
break;
case 3:
InchesToCentimetersConversion(conversionValue);
break;
case 4:
CentimetersToInchesConversion(conversionValue);
break;
case 5: /* here you CAN use fall-through */
default:
printf("Program exiting.");
break;
}
Putting all the pieces together, you can do something like the following:
#include <stdio.h>
void FahrenheitToCelsiusConversion (double conversionValue) {
double output;
output = (conversionValue - 32) / (9.0 / 5.0);
printf ("%.2f\n", output);
}
void CelsiusToFahrenheitConversion (double conversionValue) {
double output;
output = conversionValue * (9.0 / 5.0) + 32;
printf ("%.2f\n", output);
}
void InchesToCentimetersConversion (double conversionValue) {
double output;
output = conversionValue * 2.54;
printf ("%.2f\n", output);
}
void CentimetersToInchesConversion (double conversionValue) {
double output;
output = conversionValue / 2.54;
printf ("%.2f\n", output);
}
int main (void) {
int conversionChoice;
double conversionValue;
printf ("\nSelect from the menu below to convert temperature or linear\n"
"menus:\n\n"
" 1 Convert Fahrenheit to Celsius\n"
" 2 Convert Celsius to Fahrenheit\n"
" 3 Convert Inches to Centimeters\n"
" 4 Convert Centimeters to Inches\n"
" 5 Exit the Program\n\n"
"choice: ");
if (scanf ("%d", &conversionChoice) != 1 || conversionChoice < 1 ||
conversionChoice > 5) {
fputs ("error: invalid input, or value out of range.\n", stderr);
return 1;
}
printf ("\nEnter the value you wish to convert: ");
if (scanf ("%lf", &conversionValue) != 1) {
fputs ("error: invalid value input.\n", stderr);
return 1;
}
switch (conversionChoice) {
case 1:
FahrenheitToCelsiusConversion(conversionValue);
break;
case 2:
CelsiusToFahrenheitConversion(conversionValue);
break;
case 3:
InchesToCentimetersConversion(conversionValue);
break;
case 4:
CentimetersToInchesConversion(conversionValue);
break;
case 5: /* here you CAN use fall-through */
default:
printf("Program exiting.");
break;
}
return 0;
}
Example Use/Output
$ ./bin/tempconv
Select from the menu below to convert temperature or linear
menus:
1 Convert Fahrenheit to Celsius
2 Convert Celsius to Fahrenheit
3 Convert Inches to Centimeters
4 Convert Centimeters to Inches
5 Exit the Program
choice: 1
Enter the value you wish to convert: 212
100.00
Always compile with warnings enabled, and do not accept code until it compiles cleanly without warning. To enable warnings add -Wall -Wextra to your gcc or clang compile string. (add -pedantic for several additional warnings). For clang, instead you can use -Weverything. For VS (cl.exe on windoze), add /W3 (or use /Wall but you will get quite a few extraneous non-code related warnings). Read and understand each warning. They will identify any problems, and the exact line on which they occur. You can learn a lot by listening to what your compiler is telling you.
While not an error, C generally avoids the use of camelCase or MixedCase variable names in favor of all lower-case while reserving upper-case names for use with macros and constants. It is a matter of style -- so it is completely up to you, but failing to follow it can lead to the wrong first impression in some circles. See e.g. NASA - C Style Guide, 1994 As with anything outside the C-Standard, you are bound to find contra-indications, but generally camelCase or MixedCase are left to java or C++.
If you have any further questions, please just let me know.

I'm trying to pass data from my calcArea function to my calcCost function ,but I'm having trouble with it

I'm trying to get my calcCost function to work now. It doesn't carry over the area variable. Any ideas why it doesn't work? I got the calcArea function working,but can I use the area values for the calcCost area values? I started trying to put a pointer in there, but I'm not familiar with them a whole lot yet.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
// Define Constants
#define SALESTAX .07
#define TILEONE 0.78
#define TILETWO 1.59
#define TILETHREE 0.89
#define TILEONECASE 17.44
#define TILETWOCASE 10.89
#define TILETHREECASE 15.50
#define TILESIZE1 2.25
#define TILESIZE2 0.97222
#define TILESIZE3 1.77777
// Prototypes
void welcomeMessage(void);
char SelectChoice();
double getLength();
double getWidth();
double calcArea(double len, double wid);
double calcCost(double area);
void endMessage(void);
//integar return type, parameters are void,Richard's Flooring main function allows users to calculate room area and buy flooring.
int main (void)
{
//declare variables
double len, wid, area, tileNeeded,subTotal, taxTotal, total,cost;
double *dp;
char answer, myChoice;
dp = &area;
// Greets users and identifities program.
welcomeMessage ();
//Loop continues until user is done calculating area and buying flooring.
printf("Choice | Dimesions | Price | Sq.FT.per case|\n 1 | 18 x 18 | $%.2lf | 17.44 |\n 2 | 7 x 20 | $%.2lf | 10.89 |\n 3 | 16 x 16 | $%.2lf | 15.50 |\n",TILEONE, TILETWO, TILETHREE);
myChoice = SelectChoice();
len = getLength();
wid = getWidth();
// calcArea function is a double return type, it calculates the Area entered in by the user, its parameters are double len and double wid
area = calcArea(len,wid);
printf("The area of your room is: %g square feet.\n",area);
calcCost(area);
//Provides users with publisher's name.
endMessage ();
return 0;
}
// no return type, tells users what kind of program they are using, and voids any parameters.
void welcomeMessage (void)
{
printf("Welcome to Richard's Flooring\n");
system ("pause");
return ;
}
// no return type, allows user to select choice
char SelectChoice()
{
char myChoice;
do
{
printf("\nWhich tile choice would you like: ");
scanf(" %c", &myChoice);
switch(myChoice)
{
case '1':
printf("You chose choice: 1");
break;
case '2':
printf("You chose choice: 2");
break;
case '3':
printf("You chose choice: 3");
break;
default:
printf("\nINVALID CHOICE 1 - 3 only!");
}
}
while (myChoice > '3'|| myChoice < '1');
return myChoice;
}
double getLength()
{
double len;
// loop continues until positive numbers are entered.
do
{
printf("\nEnter length of room in feet: ");
scanf(" %lf", &len);
if (len <= 0)
printf("\nLength must be positive number.");
}
while (len <=0);
return len;
}
double getWidth()
{
double wid;
// loop continues until positive numbers are entered.
do
{
printf("\nEnter width of room in feet: ");
scanf(" %lf", &wid);
if (wid <= 0)
printf("\nWidth must be positive number.");
}
while (wid <=0);
return wid;
}
// Double return type, which is returning Area. Calculates the Area in a square or rectangle with the formula length * width. Accepts parameters from double len and double wid.
double calcArea(double len, double wid)
{
double area;
area = (len * wid);
return area;
}
double calcCost(double area)
{
SALESTAX ;
double len, wid, tileNeeded,subTotal, taxTotal, total,cost;
char answer, myChoice;
area = calcArea(len,wid);
do
{
char myChoice;
if (myChoice == '1')
{
tileNeeded = area/TILESIZE1;
}
else if (myChoice == '2')
{
tileNeeded = area/TILESIZE2;
}
else if (myChoice == '3')
{
tileNeeded = area/TILESIZE3;
}
printf("You will need %.2lf pieces of tile\n", tileNeeded);
subTotal = tileNeeded * TILETHREE;
printf("Your subtotal is: $%.2lf \n", subTotal);
taxTotal = subTotal * SALESTAX;
printf("Your sales tax comes out to be: $%.2lf \n", taxTotal);
total = taxTotal + subTotal;
printf("Your grand total is: $%.2lf \n",total);
printf("Would you like to measure another room?\n y or n:");
scanf(" %c", &answer);
}
while (answer == 'y'|| answer == 'Y');
}
// no return type, tells users Richard made the program, voids any parameters
void endMessage (void)
{
printf("\nThese results were provided by Richard Triplett\n");
system ("pause");
return ;
}
In main you have these lines which calculate the area and pass it to calcCost:
area = calcArea(len,wid);
printf("The area of your room is: %g square feet.\n",area);
calcCost(area);
This should work correctly but in calcCost you have:
double len, wid, tileNeeded,subTotal, taxTotal, total,cost;
char answer, myChoice;
area = calcArea(len,wid);
This recalculates the area on the basis of the len and wid variables defined in calcCost. Both of these are never set to a specific value and thus their values are indeterminate which leads to the overall area being indeterminate.
If you remove the area = calcArea(len,wid); line from calcCost then you will at least be using the correct value of area.
You will also have issues with myChoice as again this is redefined within calcCost and will have an indeterminate value. The simplest solution is probably to make myChoice an additional parameter to calcCost and pass it in from main.
The do loop in calcCost also doesn't work as required. It would return exactly the same answer every time 'y' or 'Y' was pressed. The do loop should probably be migrated into main but I have just removed it entirely for now.
Changes needed:
in main
calcCost(area,myChoice);
in calcCost
double calcCost(double area, char myChoice)
{
double tileNeeded,subTotal, taxTotal, total,cost;
if (myChoice == '1')
{
tileNeeded = area/TILESIZE1;
}
else if (myChoice == '2')
{
tileNeeded = area/TILESIZE2;
}
else if (myChoice == '3')
{
tileNeeded = area/TILESIZE3;
}
printf("You will need %.2lf pieces of tile\n", tileNeeded);
subTotal = tileNeeded * TILETHREE;
printf("Your subtotal is: $%.2lf \n", subTotal);
taxTotal = subTotal * SALESTAX;
printf("Your sales tax comes out to be: $%.2lf \n", taxTotal);
total = taxTotal + subTotal;
printf("Your grand total is: $%.2lf \n",total);
}

Intro to C: Addition and Looping

I'm continuing on my quest to mastery C and I'm currently working on an exercise to have my rudimentary calculator continuously to prompt me for two operands and a operator. If the operator is not a '+', it displays an error message. Right now, I'm running into a few problems.
When I enter '+' it shows up two times. There is NOTHING I can find in my code that indicate that this would happen.
The first operand exhibits the same problem. I also do not know how to tell my code that I am done inputting.
Second operand is fine, but I still do not know how to terminate input.
Right after it shows the results, it loops back correctly but gives me an error message before prompting again.
http://tinypic.com/r/34ew5cx/6
NOTE: I know that you use lf to read double numbers in scanf, but for some reason lf isn't working for me and f is working just fine so disregard :)
Any observations are appreciated, along with any general suggestions on how to format code/ask questions on this site/how to approach problems like this. Thanks for your help!
int main () {
char mychar;
int a;
double op1;
double op2;
printf("Welcome to Andrew Hu's calculator program!\n"); //Greeting
while(1)
{ printf("Enter a mathematical operation to perform:\n");
scanf("%c", &mychar);
if(mychar == '+') //Valid Operators
a = 1;
else
a = 0;
if(a == 0) //Operator Checker, error if invalid
printf("\nError, not a valid operator\n");
else if(a == 1){
printf("%c\n", mychar),
printf("Enter OP1:\n"),
scanf("%f", &op1),
printf("%f\n", op1),
printf("Enter OP2:\n"),
scanf("%f\n", &op2),
printf("%f\n", op2),
printf("Result of %f %c %f = %f\n",
op1, mychar, op2, (op1 + op2) );
}
}
This is a typical case where your teacher/tutor/book/online tutorial/whatever suggests that using scanf() is a good idea, whereas it really isn't. You should also not make any assumptions about line endings, and as a very last and marginal sidenote, you should structure your code better (formatting and consistency regarding curly braces included).
What I suggest you do is leave poor scanf() alone, it doesn't always do what you think it does, this is especially the case when there are single characters, strings and newline characters to read. Instead, you'd be better off reading a line and parsing and/or validating it. It will also be much simpler if you do it correctly.
I also do not know how to tell my code that I am done inputting.
Well, you decide that. How about a quit operator? Example:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char buf[0x100] = { 0 };
while (1) {
// If the user has entered "q", we enter the loop
fgets(buf, sizeof(buf), stdin);
if (buf[0] == 'q') break;
char *end;
float op1 = strtof(buf, &end); // parse 1st operand
while (isspace(*end)) {
end++;
}
char op = *end++; // get operator
float op2 = strtof(end, NULL); // parse 2nd operand
float r;
// do the calculation
switch (op) {
case '+':
r = op1 + op2;
break;
case '-':
r = op1 - op2;
break;
case '*':
r = op1 * op2;
break;
case '/':
r = op1 / op2;
break;
default:
fprintf(stderr, "Error: invalid operator '%c'\n", op);
continue;
break;
}
// print the result
printf("%f %c %f = %f\n", op1, op, op2, r);
}
return 0;
}
First thing, you need %lf in scanf to read a double, otherwise you just read a float and store it in half the double...
scanf("%lf", &op1),
This is not needed for printf because every float argument is first promoted to double...

Resources