just started reading a C++ book and one of the practice problems was to write a small calculator that takes as input one of the four arithmetic operations, the two arguments to those operations, and then prints out the results.
Sadly, the program works up until the user inputs the arithmetic option.
So if I chose to do multiplication, id write "Multiplication" and it was just stay there and not do anything after.
Image of the problem im having
#include <iostream>
#include <string>
using namespace std;
int main(){
// Simple calculator program
// Declaring three variables
float numberOne;
float numberTwo;
string operationOption;
// Asking the user which two numbers he/she will use
cout << "Enter the first number you would like to apply a arithmetic operation to: ";
cin >> numberOne;
cin.ignore();
cout << "Now enter the second number: ";
cin >> numberTwo;
cin.ignore();
// Using cin to input users selection
cout << "Enter the operation you want to perform." << endl;
cout << "The options you have are: " << endl;
cout << "Multiplication, Subraction, Division and Addition: " << endl;
cin >> operationOption;
cin.ignore();
cin.get();
// Where it all happens
if ( operationOption == "Multiplication" ) {
cout << "The first number multiplied by the second number is: " << numberOne * numberTwo << endl;
} else if ( operationOption == "Division" ) {
cout << "The first number divided by the second number is: " << numberOne / numberTwo << endl;
} else if ( operationOption == "Subtraction" ) {
cout << "The first number subtracted by the second number is: " << numberOne - numberTwo << endl;
} else if ( operationOption == "Addition ") {
cout << "The first number added to the second number is: " << numberOne + numberTwo << endl;
} else {
cout << "You entered an invalid option.";
};
}
Remove line :
cin.get();
will solve your problem
Related
I'm trying to make the program exit properly without it. I have '|' as my exit, if its the first thing I do when first running, it closes fine. But after entering values and printing them, afterwards entering '|' to exit.
It prints out:
"The smaller value is 0
The larger is previous second value" // want to remove this from showing
int main()
{
double first = 0, second = 0;
while(cin.good()){
char exit;
cout << "Enter '|' to exit.\n";
cout << "Enter two numbers:";
cin >> first >> second;
exit = cin.peek();
if(exit=='|'){
break;}
else{
if(first<second){
cout << "\nThe smaller value is " << first << "\nThe larger value is " << second << endl;
}
else if(first>second){
cout << "\nThe smaller value is " << second << "\nThe larger value is " << first << endl;
}
}
}
}
In your code, you've assumed that the input from your users will be limited to something usable as a double. This isn't necessarily the case. The issue that you're running into isn't related to the statement exit = cin.peak(); but to cin >> first >> second; You can test this by entering any non-numerical input into your program and watching it fail by assigning a 0 to the first and leaving second as is.
In short, because the conversion of the input into a double fails, you get an indeterminate value for first and then your program moves on.
You can use the following code as an example. In this, I first populate my variables as strings, then attempt a conversion after the fact.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string str_first, str_second;
double first = 0, second = 0;
while(cin.good()){
cout << "Enter '|' to exit.\n";
cout << "Enter two numbers:";
cin >> str_first >> str_second;
if( (str_first.compare("|") == 0) || (str_second.compare("|") == 0) ){
cout << "\nThanks for playing\n" << endl;
break;}
else{
first = strtod (str_first.c_str(), NULL);
second = strtod (str_second.c_str(), NULL);
if(first<second){
cout << "\nFirst is small: The smaller value is " << first << "\nThe larger value is " << second << endl;
}
else if(first>second){
cout << "\nSecond is small: The smaller value is " << second << "\nThe larger value is " << first << endl;
}
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
#ifndef CALC_H
#define CALC_H
class calc
{
double numb1;
double numb2;
public:
calc();
void FUN_SUM();
void FUN_Subtraction();
void FUN_Multiplication();
void FUN_Division();
void FUN_Power();
void FUN_Squareroot();
void FUN_Switch();
void FUN_Loob();
};
#endif // CALC_H
#include "calc.h"
#include <iostream>
#include <cmath>
using namespace std;
calc::calc()
{
numb1 = 0;
numb2 = 0;
}
void calc::FUN_SUM()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Sum;
Result_Of_Sum = numb1+numb2;
cout << "The result of Sum = " << Result_Of_Sum << endl;
}
void calc::FUN_Subtraction()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Subtraction;
Result_Of_Subtraction = numb1 - numb2;
cout << "The result of Subtraction = " << Result_Of_Subtraction << endl;
}
void calc::FUN_Multiplication()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Multiplication;
Result_Of_Multiplication = numb1*numb2;
cout << "The result of Multiplication = " << Result_Of_Multiplication << endl;
}
void calc::FUN_Division()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Division ;
Result_Of_Division = numb1/numb2;
cout << "The result of Division = " << Result_Of_Division << endl;
}
void calc::FUN_Power()
{
cout << "Enter number 1 " << endl;
cin >> numb1;
cout << "Enter number 2 " << endl;
cin >> numb2;
double Result_Of_Power;
Result_Of_Power = pow(numb1,numb2);
cout << "The result of Power = " << Result_Of_Power << endl;
}
void calc::FUN_Squareroot()
{
cout << "Enter the tow number you want Square root \n";
cin >> numb1;
double Result_Of_Square_root;
Result_Of_Square_root = sqrt(numb1);
cout << "The result of Square root = " << Result_Of_Square_root << endl;
}
void calc::FUN_Switch()
{
int S;
cout << "Enter the number you operator do you want do it " << endl;
cout << "1- Addition" << endl;
cout << "2- Subtraction" << endl;
cout << "3- Multiplication" << endl;
cout << "4- Division" << endl;
cout << "5- Power" << endl;
cout << "6- Square Root" << endl;
cout << "7- Exit" << endl;
cin >> S;
switch (S)
{
case 1:
FUN_SUM();
break;
case 2:
FUN_Subtraction();
break;
case 3:
FUN_Multiplication();
break;
case 4:
FUN_Division();
break;
case 5:
FUN_Power();
break;
case 6:
FUN_Squareroot();
break;
default :
break;
}
}
void calc::FUN_Loob()
{
char L;
do
{
FUN_Switch();
cout << "Do you want do another operator ( 'y' or 'n'?) \n";
cin >> L;
if (L== 'y' || L=='Y' || L=='n' || L=='N')
continue;
else
cout << "you are enter roang later\n";
}
while (L == 'Y' || L == 'y' );
}
#include <iostream>
#include "calc.h"
using namespace std;
int main()
{
cout << "Welcome to my simple Calculator\n";
calc simple_calc;
simple_calc.FUN_Loob();
cout << "\n Tank you for use my App :) :) " << endl;
return 0;
}
my question is how i can enable user Calc any value with operators like regular Calculator
for example 1+9*8-1+5 i want my program do like that but i don`t know how ?? :( :(
Writing a calculator is not an easy task, as there is more involved:
Operator Precedence
Grouping
Evaluating of expressions
Operator Precedence
Operator precedence is the grouping of operations, such as performing all multiplication and division before addition and subtraction. A calculator program should handle precedence without parenthesis (grouping).
Grouping
A more advanced calculator will allow grouping of expressions, using parenthesis. The calculator should be able to evaluate the inner most expression and work outward.
Evaluating of Expressions
This means allowing more than 1 digit numbers, and whitespace between numbers and symbols. Also, once the expression is parsed, it needs to be evaluated. The calculator should call the appropriate functions based on the operation (specified by the User).
I suggest you allow the User to enter an expression, and your program read it in as a string. Your program will then parse the string, then evaluate the expression(s).
Search the web and StackOverflow for "c++ calculator" for examples.
I'm a beginner in c++ so I'm just messing around with some stuff while reading articles and books. But I spent 20 minutes re-reading this over and over again and I can't tell what's wrong with it.
#include <iostream>
#include <string>
using namespace std;
int main ()
{
cout << "Hello there, this is your personal simple calculator.";
cin.get();
cout << "Type in what you want to do. (Addition, Subtraction, Multiplication, Division)"<< endl;
string c;
getline (cin, c);
if (c == "Addition")
{
string a_1;
string a_2;
cout << "You chose addition. Press enter" << endl ;
cin.get();
cout << "Type in the first value: ";
getline( cin, a_1);
cout << "Type in the second value: ";
getline (cin, a_2);
cout << a_1 << " + " << a_2 << " = " << a_1 + a_2 << endl;
}
else
{
cout << "You spelled it wrong.";
return 0;
}
if ( c == "Subtraction")
{
string s_1;
string s_2;
cout << "You chose subtraction. Press enter" << endl ;
cin.get();
cout << "Type in the first value: ";
getline (cin, s_1);
cout << "Type in the second value: ";
getline (cin, s_2);
cout << s_1 << " - " << s_2 << " = " << s_1 - s_2 << endl;
}
}
I get this as the only error
42 83 C:\Users\Jason\Desktop\Lesson - Header Files\LH1.cpp [Error] no match for 'operator-' in 'first_argument - second_argument'
I don't get it. The addition sign works and everything but the subtraction works.
So I messed around with something else
cout << first_argument << " - " << second_argument << " = " << first_argument - second_argument << endl;
But that subtraction part works fine. I don't get it. Help please
string can deal with text. When you add two strings, they are concatenated ("2"+"2"=="22", not "4"). String doesn't have operator-.
To deal with floating-point numbers, use double. To deal with integers, use int:
double d1, d2;
//some output
cin >> d1;
//some output
cin >> d2;
cout << d1 << " - " << d2 << " = " << (d1-d2) << '\n';
The addition part works because string + string results in stringstring. It appends the two strings and returns a new string.
But subtracting two strings doesn't mean anything.
What I believe you actually want to do is convert the strings into numbers and then subtract the numbers.
To do that, you need to use something like the following:
double val_1, val_2;
cin >> val_1;
cin >> val_2;
cout << "result is " << (val_1 - val_2) << endl;
I put the subtraction inside parenthesis because I believe the << aka "shift" operator is on the same level as multiplication, which means that without them it would try to evaluate ("result is " << val_1) - (val_2 << endl).
Since I am not sure on operator precedence I checked http://en.cppreference.com/w/cpp/language/operator_precedence and found that << is lower than subtraction, so my parenthesis weren't necessary.
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
cout << "Hello there, this is your personal simple calculator.";
cin.get();
cout << "Type in what you want to do. (Addition, Subtraction, Multiplication, Division)" << endl;
string c;
getline(cin, c);
if (c == "Addition")
{
int a_1;
int a_2;
cout << "You chose addition. Press enter" << endl;
cin.get();
cout << "Type in the first value: ";
cin >> a_1;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Type in the second value: ";
cin >> a_2;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << a_1 << " + " << a_2 << " = " << a_1 + a_2 << endl;
}
else if (c == "Subtraction")
{
int s_1;
int s_2;
cout << "You chose subtraction. Press enter" << endl;
cin.get();
cout << "Type in the first value: ";
cin >> s_1;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Type in the second value: ";
cin >> s_2;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << s_1 << " - " << s_2 << " = " << s_1 - s_2 << endl;
}
else
{
cout << "You spelled it wrong.";
return 0;
}
}
Use if else statements because otherwise your code won't have a chance to check to see if the user is trying to Subtract. It is best to leave the else at the very end.
Also changed the strings to ints because strings cannot subtract as they are not numbers.
On a final note, I used the cin.clear() & cin.ignore() to flush the cin buffer.
I need help with a program for school. We had to write a program that asks the user for information about a baseball player. We need to calculate the players batting average with their games played, number of times at bat and number of hits. I am running into an issue where my computation for the average is outputting a set number and not performing any computations. I am entering whole integers for all the variables that are used for calculation. So i would input numbers like 1, 4 , 10 etc... As the program stands the value my formula is setting itself equal to is 15903.876. All of my variables used for the average formula are declared as integers and the batting average itself is declared as a double. I have done some debugging my self and found that the computation messes up when it divides the number of times at bat by the number of hits. If anyone could help me figure out the issue i would appreciate it.
//libaries
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
class battingAverage
{
public:
string pName;
int nBats;
int tHits;
int gPlayed;
int gcalled;
double average;
double average1;
double playeraverage;
};
int main()
{
string numberPlayers;
int nplayers;
//enters the number of players the user wants to enter data for
cout << "Enter the number of players you want to enter data for: ";
cin >> numberPlayers;
cout << endl;
//converts the value of numberPlayers to nplayers
istringstream convert(numberPlayers);
//sets integer nplayers equal to the value of the string numberPlayers
if(! (istringstream(numberPlayers) >> nplayers) )
{
nplayers = 0;
}
cout << "This program calculates the batting average of baseball players.\nYou may enter data for " << nplayers << " players." << endl;
battingAverage ba[nplayers];
int index = 0;
//while statement to get data
while(index < nplayers)
{
cout << "Enter the players last name: " << endl;
cin >> ba[index].pName;
cout << "Enter the number of games the player played: " << endl;
cin >> ba[index].gPlayed;
cout << ba[index].gPlayed << endl;
cout << "Enter the number of games the player was called in for: " << endl;
cin >> ba[index].gcalled;
cout << ba[index].gcalled << endl;
cout << "Enter the number of times the player was at bat: " << endl;
cin >> ba[index].nBats;
cout << ba[index].nBats << endl;
cout << "Enter the number of time the player hit: " << endl;
cin >> ba[index].tHits;
cout << ba[index].tHits << endl;
if(ba[index].tHits > ba[index].nBats)
{
cout << "Enter a valid value for the number of times the player hit: ";
cin >> ba[index].tHits;
}
cout << endl;
index++;
}
//rounds average to 3 decimal places
cout << fixed << setprecision( 3 );
//average formula
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
cout << ba[index].playeraverage << endl << endl;//just temp line to check calculation of average.
ba[index].average = .000;
ba[index].average1 = .099;
while(ba[index].average < 1 && ba[index].average1 < .899)
{
ba[index].average +=.100;
ba[index].average1 += .1;
//prints chart
cout << setprecision( 1 ) << ba[index].average << "00" << setprecision( 3 ) << setw(12) << ba[index].average1 << endl;
}
cout << "1.000" << setw(12) << "1.000" << endl;
//version of system pause
cout << "\nPress enter to continue...";
cin.sync();
cin.ignore();
return 0;
}
On this line:
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
You have this expression:
(ba[index].nBats / ba[index].tHits)
Because both nBats and tHits are integers, you're using only integer math.
The answer will be an integer.
For example:
nBats = 10 & tHits = 3, you'd expect the expression to be 3.333.
But it would only be 3
To fix this, I recommend changing to:
((double)ba[index].nBats / ba[index].tHits)
Same thing again with the expression about gPlayed and gcalled.
Your value of index is wrong during the calculations.
I found this as soon as I put your code in a debugger and stepped through it, something you really should have done yourself.
You start with int index = 0;, and increment it as the user puts in each player's data.
At the end of the input-loop, index is now the same as the number of players.
(eg. if you had 5 players, index is now 5, and the player data is stored in ba[0], ba[1], ba[2], ba[3], and ba[4])
Note that at this point ba[5] is NOT valid data. But that is exactly where ba[index] is!
You do all your calculations on ba[index], which is invalid data, and you wonder why you get meaningless results?
I recommend you set index back to 0 before starting your calculations, and make another loop that does the necessary calculations for each player 0...4.
How do you check for non-numeric input using C++? I am using cin to read in a float value, and I want to check if non-numerical input is entered via stdin. I have tried to use scanf using the %d designator, but my output was corrupted. When using cin, I get the correct format, but when I enter, a string such as "dsffsw", I get an infinite loop.
The commented code was my attempt to capture the float, and type cast it as string, and check if it is a valid float, but the check always comes up false.
I have tried using other methods I have found on the message boards, but they want to use scanf in C and not cin in C++. How do you do this in C++? Or in C if it is not feasible.
while (!flag) {
cout << "Enter amount:" << endl;
cin >> amount;
cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl;
//if (!strtod(((const char *)&amount), NULL)) {
// cout << "This is not a float!" << endl;
// cout << "i = " << strtod(((const char *)&amount), NULL) << endl;
// //amount = 0.0;
//}
change = (int) ceil(amount * 100);
cout << "change = " << change << endl;
cout << "100s= " << change/100 << endl;
change %= 100;
cout << "25s= " << change/25 << endl;
change %= 25;
cout << "10s= " << change/10 << endl;
change %= 10;
cout << "5s= " << change/5 << endl;
change %= 5;
cout << "1s= " << change << endl;
cout << "END The amount you entered is: " << amount << endl;
}
return 0;
}
int amount;
cout << "Enter amount:" << endl;
while(!(cin >> amount)) {
string garbage;
cin.clear();
getline(cin,garbage);
cout << "Invalid amount. "
<< "Enter Numeric value for amount:" << endl;
}
I think you task relates to the so called defensive programming, one of it`s ideas is to prevent situations like one you described (function expects one type and user enters another).
I offer you to judge whether input is correct using method that returns stream state , which is good(),
so I think it will look something like this:
int amount = 0;
while (cin.good()) {
cout << "Enter amount:" << endl;
cin >> amount;