While loop and boolean function - c++

Hello guys I'm not an expert on the subject so please excuse my pour skills. I finished my program and it works fine (calculator). The problem is that now I don't know where to locate the while loop in conjunct with the Boolean function to repeat the process once it is done with a task (once the program completes a math operation). Any help, comment or suggestion will be greatly appreciated. Thank you.!!
#include <iostream>
#include <math.h>
#include <cmath>
int main()
{
double a=0.0;
double b=0.0;
double c=0.0;
bool repeat = true;
do {
using namespace std;
int x;
cout << "**********************************" << endl;
cout << "| |" << endl;
cout << "| 0 - Quit |" << endl;
cout << "| 1 - Add |" << endl;
cout << "| 2 - Subtract |" << endl;
cout << "| 3 - Divide |" << endl;
cout << "| 4 - Multiply |" << endl;
cout << "| 5 - Raise X to the power Y |" << endl;
cout << "| 6 - Sine ( x ) |" << endl;
cout << "| 7 - Cosine ( x ) |" << endl;
cout << "| 8 - Tangent ( x ) |" << endl;
cout << "**********************************" << endl;
cout << "Enter a selection, please: " << endl;
cin >> x;
switch (x)
{
{
case 1:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter second value " << endl;
cin >> b;
c=a+b;
cout << "The addition of " << a << " and "<< b << "is" << c << endl;
break;
bool repeat = true;
}
{
case 2:
cout << " Enter the first value" << endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a-b;
cout << "The subtraction of " << a << " and " << b << " is: " << c << endl;
break;
bool repeat = true;
}
{
case 3:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a/b;
cout << " The division os " << a << " and " << b << "is" << c << endl;
break;
bool repeat = true;
}
{
case 4:
cout << " Enter the first value" <<endl;
cin >> a ;
cout << " Enter the second value " << endl;
cin >> b;
c=a*b;
cout << " The product of " << a << " times " << b << " is " << c << endl;
break;
bool repeat = true;
}
{
case 5:
cout << " Enter the value to be exponentiated " <<endl;
cin >> a ;
cout << " Enter the exponent" << endl;
cin >> b;
c= pow(a,b);
cout << a << " Rased to the power of " << b << " is: " << c << endl;
break;
bool repeat = true;
}
{
case 6:
cout << " Enter the value that you want the sine to be taken of" <<endl;
cin >> a ;
c=sin(a);
cout << " The sine of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 7:
cout << " Enter the value that you want the cosine to be taken of" <<endl;
cin >> a ;
c=cos(a);
cout << " The cosine of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 8:
cout << " Enter the value that you want the tangent to be taken of" <<endl;
cin >> a ;
c=tan(a);
cout << " The tangent of " << a << " is: " << c << endl ;
break;
bool repeat = true;
}
{
case 0:
cout << "Ending the program" << endl;
return 0;}
break;
bool repeat = true;
}
} while (repeat = true );
return 0;
}

So here is few moments.
Call
using namespace std;
just believe - is bad idea;
In conditions like if() or while() use operator == instead of =. Because "=" - is assigne operator, and return value depended on success of operation. And "==" is compare operator.
Ow and figure one more missunderstanding. Using bool rezult = true; is wrong. You should use rezult = true; Because every time when you write type specifer you create local variable in context of case, and this don`t affect rezult declared in main
My opinion for your question is little change:
from:
do{
int x;
...
case 0:
cout << "Ending the program" << endl;
return 0;}
break;
bool repeat = true;
}
} while (repeat = true );
to
do{
int x;
...
case 0:
cout << "Ending the program" << endl;
repeat = false;}
break;
}
} while (repeat == true);
and if you need a bit more calculations you can wrapped it to new cicle something like:
while(new_condtion == true) {
do {
...
} while(repeat == true);
//change new_condtion
}

Don't redefine repeat within switch case. This creates a different variable named repeat which, although it has the same name, is not the variable named repeat defined before the loop. This is what you get when you copy a definition of the form bool repeat = true; into multiple places.
The continuation condition for the loop (repeat = true) will also loop forever. Comparison is two = signs, not one.

Related

How to store multiple string inputs and displaying it after

I'm just starting in studying C++, and I am doing a simple challenge which is GWA Calculator, but I am having a problem finding out how to store the multiple strings input (which is the Subjects/Course) and displaying it after together with the Units and Grades. I am really sorry, but I tried finding out how and I couldn't find an answer. Hope you can help me out.
#include <stdlib.h>
using namespace std;
void calculateGWA();
int main()
{
system("cls");
int input;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
cout << "\t\t| GWA Calculator |" << endl;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
cout << "\t\t| MENU:\t\t\t\t\t\t\t " << "|" << endl;
cout << "\t\t| 1. Calculate GWA (General Weighted Average)\t\t " << "|" << endl;
cout << "\t\t| 2. Calculate CGWA (Cummulative Weighted Average) " << "|" << endl;
cout << "\t\t| 4. Exit Application\t\t\t\t\t " << "|" << endl;
cout << "\t\t| |" << endl;
cout << "\t\t -------------------------------------------------------------------------- " << endl;
sub:
cout << "\t\tEnter your choice: ";
cin >> input;
switch(input)
{
case 1:
calculateGWA();
break;
case 2:
//calculateCGPA();
break;
case 3:
main();
break;
case 4:
exit(EXIT_SUCCESS);
break;
default:
cout << "You have entered wrong input.Try again!\n" << endl;
goto sub;
break;
}
}
void calculateGWA()
{
int q;
system("cls");
cout << "-------------- GWA Calculator -----------------"<<endl;
cout << " How many course(s)?: ";
cin >> q;
char c_name[50];
float unit [q];
float grade [q];
cout << endl;
for(int i = 0; i < q; i++)
{
cout << "Enter the Course Name " << i+1 << ": ";
cin >> c_name;
cout << "Enter the Unit " << c_name << ": ";
cin >> unit[i];
cout << "Enter the Grade " << c_name << ": ";
cin >> grade[i];
cout << "-----------------------------------\n\n" << endl;
}
float sum = 0;
float tot;
for(int j = 0; j < q; j++)
{
tot = unit[j] * grade[j];
sum = sum + tot;
}
float totCr = 0;
for(int k = 0; k < q; k++)
{
totCr = totCr + unit[k];
}
system("cls");
// PRINTS OUT THE COURSES - UNITS - GRADES AND GWA //
cout << "\t\t =============================================================== " << endl;
cout << "\t\t| COURSE | UNIT | GRADE |" << endl;
cout << "\t\t =============================================================== " << endl;
cout << "Total Points: " << sum << " \n Total Credits: " << totCr << " \nTotal GPA: " << sum/totCr << " ." << endl;
cout << c_name << "\n" << endl;
cout << "===================================" << endl;
sub:
int inmenu;
cout << "\n\n\n1. Calculate Again" << endl;
cout << "2. Go Back to Main Menu" << endl;
cout << "3. Exit This App \n\n" << endl;
cout << "Your Input: " << endl;
cin >> inmenu;
switch(inmenu)
{
case 1:
calculateGPA();
break;
case 2:
main();
break;
case 3:
exit(EXIT_SUCCESS);
default:
cout << "\n\nYou have Entered Wrong Input!Please Choose Again!" << endl;
goto sub;
}
}

Looping for calculators

The program will take in floating-point numbers and operators from the user and perform the required calculations, printing out the results. The result of each calculation will serve as an operand for the next calculation.
So, I am not sure if I am doing this correctly by using switch statements ? Is there a better way of doing it ? Maybe, by using a do - while loop ? I am really confused.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float firstOperand;
cout << "Enter a number: ";
cin >> firstOperand;
cout << endl;
cout << "Choose an instruction code: " << endl << endl;
cout << "1) (+) for addition. " << endl;
cout << "2) (*) for multiplication. " << endl;
cout << "3) (p) for power. " << endl;
cout << "4) (c) to clear the current result. " << endl;
cout << "5) (-) for subtraction. " << endl;
cout << "6) (/) for divison. " << endl;
cout << "7) (s) for square root. " << endl;
cout << "8) (q) to quit the program. " << endl << endl;
int choice;
cin >> choice;
cout << endl;
float secondOperand;
cout << "Enter the second number: ";
cin >> secondOperand;
cout << endl;
switch (choice)
{
case 1:
{
float resultOne = firstOperand + secondOperand;
cout << "The result of the calculation is " << resultOne << endl;
}
case 2:
{
float thirdOperand;
cout << "Enter another number ";
cin >> thirdOperand;
cout << endl;
cout << "Choose an instruction code: " << endl << endl;
cout << "1) (+) for addition. " << endl;
cout << "2) (*) for multiplication. " << endl;
cout << "3) (p) for power. " << endl;
cout << "4) (c) to clear the current result. " << endl;
cout << "5) (-) for subtraction. " << endl;
cout << "6) (/) for divison. " << endl;
cout << "7) (s) for square root. " << endl;
cout << "8) (q) to quit the program. " << endl << endl;
float resultTwo = resultOne + thirdOperand;
cout << "The result of the calculation is " << resultTwo << endl;
}
break;
}
system("pause");
return 0;
}
Try this code:
#include <iostream>
#include <math.h>
using namespace std;
int main(){
float firstOperand, secondOperand, result;
int choice, quit = 0;
cout << "Enter a number: ";
cin >> firstOperand;
cout << endl;
while (1){
cout << "The first operand is " << firstOperand << endl;
cout << "\nChoose an instruction code: " << endl;
cout << "1) (+) for addition. " << endl;
cout << "2) (*) for multiplication. " << endl;
cout << "3) (p) for power. " << endl;
cout << "4) (c) to clear the current result. " << endl;
cout << "5) (-) for subtraction. " << endl;
cout << "6) (/) for divison. " << endl;
cout << "7) (s) for square root. " << endl;
cout << "8) (q) to quit the program. " << endl << endl;
cin >> choice;
cout << endl;
if (choice == 8){
cout << "Quitting the program..." << endl;
break;
}
cout << "Enter the second number: ";
cin >> secondOperand;
cout << endl;
switch(choice){
case 1: result = firstOperand + secondOperand;
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
case 2: result = firstOperand * secondOperand;
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
case 3: result = pow(firstOperand, secondOperand);
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
case 4: result = 0;
cout << "The result has been cleared to " << result << endl;
cout << "Enter the first operand: ";
cin >> firstOperand;
cout << endl;
break;
case 5: result = firstOperand - secondOperand;
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
case 6: if(secondOperand){
result = firstOperand / secondOperand;
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
}
else{
cout << "Second operand is " << secondOperand << "Choose again!" << endl;
}
case 7: result = sqrt(secondOperand);
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
default:cout << "Invalid input. Enter again!" << endl;
break;
}
}
}
The main code is wrapped inside an infinite while loop with a quit condition. The break statement is used to exit the while loop when the user wishes to.
Note: The input for the operator is the number and not the symbol. You will have to change choice variable to char in case you want to use the symbol as the input.
Update: The following code is for character inputs.
#include <iostream>
#include <math.h>
using namespace std;
int main(){
float firstOperand, secondOperand, result;
int quit = 0;
char choice;
cout << "Enter a number: ";
cin >> firstOperand;
cout << endl;
while (1){
cout << "The first operand is " << firstOperand << endl;
cout << "\nChoose an instruction code: " << endl;
cout << "1) (+) for addition. " << endl;
cout << "2) (*) for multiplication. " << endl;
cout << "3) (p) for power. " << endl;
cout << "4) (c) to clear the current result. " << endl;
cout << "5) (-) for subtraction. " << endl;
cout << "6) (/) for divison. " << endl;
cout << "7) (s) for square root. " << endl;
cout << "8) (q) to quit the program. " << endl << endl;
cin >> choice;
cout << endl;
if (choice == 'q'){
cout << "Quitting the program..." << endl;
break;
}
cout << "Enter the second number: ";
cin >> secondOperand;
cout << endl;
switch(choice){
case '+': result = firstOperand + secondOperand;
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
case '*': result = firstOperand * secondOperand;
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
case 'p': result = pow(firstOperand, secondOperand);
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
case 'c': result = 0;
cout << "The result has been cleared to " << result << endl;
cout << "Enter the first operand: ";
cin >> firstOperand;
cout << endl;
break;
case '-': result = firstOperand - secondOperand;
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
case '/': if(secondOperand){
result = firstOperand / secondOperand;
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
}
else{
cout << "Second operand is " << secondOperand << "Choose again!" << endl;
}
case 's': result = sqrt(secondOperand);
cout << "The result of the calculation is " << result << endl;
firstOperand = result;
break;
default: cout << "Invalid input. Enter again!" << endl;
break;
}
}
}
Here is one possible version on the code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int select_operation()
{
int choice;
cout << "Choose an instruction code: " << endl << endl;
cout << "1) (+) for addition. " << endl;
cout << "2) (*) for multiplication. " << endl;
cout << "3) (p) for power. " << endl;
cout << "4) (c) to clear the current result. " << endl;
cout << "5) (-) for subtraction. " << endl;
cout << "6) (/) for divison. " << endl;
cout << "7) (s) for square root. " << endl;
cout << "8) (q) to quit the program. " << endl << endl;
cin >> choice;
cout << endl;
return choice;
}
int main()
{
float secondOperand;
float firstOperand;
float thirdOperand;
float resultOne;
int choice;
cout << "Enter a number: ";
cin >> firstOperand;
cout << endl;
choice = select_operation();
if (choice == 8)
return 0;
else if(choice == 7)
secondOperand = .5;
else{
cout << "Enter the second number: ";
cin >> secondOperand;
}
cout << endl;
while(1)
{
switch (choice) {
case 1:
resultOne = firstOperand + secondOperand;
cout << "The result of the calculation is " << resultOne << endl;
break;
case 2:
resultOne = firstOperand * secondOperand;
cout << "The result of the calculation is " << resultOne << endl;
break;
case 3:
resultOne = pow(firstOperand,secondOperand);
cout << "The result of the calculation is " << resultOne << endl;
break;
case 4:
resultOne = 0;
cout << "The result of the calculation is " << resultOne << endl;
break;
case 5:
resultOne = firstOperand - secondOperand;
cout << "The result of the calculation is " << resultOne << endl;
break;
case 6:
if(secondOperand){
resultOne = firstOperand / secondOperand;
cout << "The result of the calculation is " << resultOne << endl;
}
break;
case 7:
resultOne = pow(firstOperand,secondOperand);
cout << "The result of the calculation is " << resultOne << endl;
break;
}
choice = select_operation();
if (choice == 8)
return 0;
else if(choice == 7)
secondOperand = .5;
else{
cout << "Enter another number ";
cin >> thirdOperand;
secondOperand = thirdOperand;
}
}
cout << endl;
firstOperand = resultOne;
return 0;
}
The above code accepts two inputs at first immediately returns if it is option 8(quit the program). if the operation is square root as it is a unary operation not taking in second operand.
Reading the 3rd operand and operator is continued until it is requested to stop.

C++ Program need help to debug

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...

Are there identifiers for strings or numbers?

I recently developed a calculator, this is the code:
/*
*All 4 operations + percentage finder + Raise to power and more....
* by Ulisse
* ulissebenedennti#outlook.com
* Feel free to take some parts of this code an put them
* in yours, but do not take all the code and change/delete
* the comments to take the credit, trust me, it doesn't
* gives the satisfaction you expect.
*/
#include <iostream> //For cin and cout
#include <iomanip> //For setprecision()
#include <windows.h> //For SetconsoleTitle()
#include <stdlib.h> //For system()
#include <cmath> //For pow()
#include <cctype> //For isdigit()
using namespace std;
int main(){
reset:
system("cls"); //Screen cleaner
system("color 0f");
SetConsoleTitle("Calculator by Ulisse");//Setting window title
char op; //Start of the variables declaration
double a, b, ra;
string p, ms, d, me, e;
p = " + ";
ms = " - ";
d = " : ";
me = " x ";
e = " = "; //End of the variable declaration
cout << "Type now '?' for help page, or another character to continue." << endl;
cin >> op;
if (op == '?'){
help:
system("cls");
cout << "Write the whole operation.\nEXAMPLE: 2 ^ 3 \n OUTPUT: 2 ^ 3 = 8"<< endl;
cout << "(+) Sum between a and b\n(-) Subtraction between a and b" << endl;
cout << "(^) Raise to power\n(%)finds the a% of b\n(x or *)Multiplicate a by b" << endl;
cout << "(: or /) Divide a by b" << endl;
system("pause");
system("cls");
goto start;
}
else{
system("cls");
while(1){
start:
cout << "CALC> ";
cin >> a;
cin >> op;
cin >> b;
//The four operations
if (op == '+'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << p << b << e << a + b << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '-'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << ms << b << e << a - b << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '*' || op == 'x'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << me << b << e << a * b << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '/' || op == ':'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << d << b << e << a / b << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '%'){
cout << "RESULT" << endl;
cout << setprecision(999) << "The " << a << "% of " << b << " is " << b / 100 * a << endl;
cout << "________________________________________________________________________________" << endl;
}
if (op == '^'){
cout << "RESULT" << endl;
cout << setprecision(999) << a << " ^ " << b << " = " << pow (a, b) << endl;
cout << "________________________________________________________________________________" << endl;
}
//Some useful functions
if (op == 'c'){
system("cls");
}
if (op == '?'){
system("cls");
goto help;
}
if (op == 'r'){
goto reset;
}
if (op == 'b'){
system("color 0c");
Beep(400,500);
cout << "CLOSING, ARE YOU SURE?(y/n)";
system("color 0c");
cin >> op;
if(op == 'y'){
cout << "Closing..." << endl;
system("cls");
system("color 0f");
system("pause");
break;
}
if(op == 'n'){
goto start;
}
}
if (op == '<'){
if (a < b){
cout << "RESULT" << endl;
cout << setprecision(999) << a << " < " << b << e << " TRUE " << endl;
cout << "________________________________________________________________________________" << endl;
}
else{
cout << "RESULT" << endl;
cout << setprecision(999) << a << " < " << b << e << " FALSE " << endl;
cout << "________________________________________________________________________________" << endl;
}
}
if (op == '>'){
if (a > b){
cout << "RESULT" << endl;
cout << setprecision(999) << a << " > " << b << e << "TRUE" << endl;
cout << "________________________________________________________________________________" << endl;
}
else{
cout << "RESULT" << endl;
cout << setprecision(999) << a << " > " << b << e << "FALSE" << endl;
cout << "________________________________________________________________________________" << endl;
}
}
if (op == '='){
if (a == b){
cout << "RESULT" << endl;
cout << setprecision(999) << a << " = " << b << " is TRUE" << endl;
cout << "________________________________________________________________________________" << endl;
}
else{
cout << "RESULT" << endl;
cout << setprecision(999) << a << " = " << b << " is FALSE" << endl;
cout << "________________________________________________________________________________" << endl;
}
}
}
}
}
This is how it works:
You write a number, then an operator(like +, - plus other functions...) and it makes the operation between the two numbers you typed depending o what is the typed operato, so if you type 4 + 3 it will output 4 + 3 = 7.
Now that you understand how it works, let us go to the qyestion...
Is there an indentifier for a number or a character? When you type a sttring or a character when you cin >> (not a number variable) the application will start printing out characters that you did never inserted:
Input
I think like this(console output) will be printed out(until you dont close the process.
So i would like to prevent the applicatin for failing when you type an invalid input for the variable and making it executes another instruction, here's what i mean:
if(anumbervariable != number || anumbervariable == string){
cout << "invalid input" << endl;
}
This isn't a real working code, it's just a representation of what i mean, or i wouldn't came hre to make you waste you lives :)
Thanks in advance.
You can do something like follows
int getNumber(){
int x;
cin >> x;
while(cin.fail()){
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "invalid input"<<endl;
cin >> x;
}
return x;
}
If you want to do a character by character thing, C++ has an isalpha() function, so you can use !isalpha(). The numeric limits thing is the max buffer that can be taken before a new line. If you print it out, it's just some large number so that it can ignore that amount of input.

C++ functions and loops

I have to write a program that simulates an ice cream cone vendor. The user inputs the number of cones, and for each cone, the user inputs the number of scoops, then the flavor(a single character) for each scoop. At the end, the total price is listed. For the pricing, 1 scoop costs 2.00, 2 scoops costs 3.00 and each scoop after 2 costs .75.
I'm having trouble with the pricing. The correct price is displayed if the user only wants one cone.
/*
* icecream.cpp
*
* Created on: Sep 14, 2014
* Author:
*/
#include <iostream>
#include <string>
using namespace std;
void welcome() {
cout << "Bob and Jackie's Ice Cream\n";
cout << "1 scoop - $1.50\n";
cout << "2 scoops - $2.50;\n";
cout << "Each scoop after 2 - $.50\n";
cout << "Ice Cream Flavors: Only one input character for each flavor.\n";
}
bool checkscoops(int scoops) {
int maxscoops = 5;
if ((scoops > maxscoops) || (scoops < 1))
return false;
else
return true;
}
bool checkcones(int cones) {
int maxcones = 10;
if ((cones > maxcones) || cones < 1)
return false;
else
return true;
}
int price(int cones, int numberofscoops) {
float cost = 0.00;
{
if (numberofscoops == 5) {
cost = cost + 5 + (.75 * 3);
}
if (numberofscoops == 4) {
cost = cost + 5 + (.75 * 2);
}
if (numberofscoops == 3) {
cost = cost + 5.75;
}
if (numberofscoops == 2) {
cost = cost + 5.00;
}
if (numberofscoops == 1) {
cost = cost + 2.00;
}
}
cout << "Total price is: " << cost << endl;
}
int buildcone(int numcones) {
char flav1, flav2, flav3, flav4, flav5;
int numberofscoops;
for (int i = 1; i <= numcones; i++) {
cout << "Enter the amount of scoops you wish to purchase. (5 max): ";
cin >> numberofscoops;
checkscoops(numberofscoops);
while (checkscoops(numberofscoops) == false) {
cout << "You are not allowed to buy more than 5 scoops and you "
"cannot buy less than one scoop. Please try again.\n";
cout << "How many scoops would you like?(5 max): ";
cin >> numberofscoops;
checkcones(numberofscoops);
}
cout << "You are buying " << numberofscoops
<< " scoops of ice cream.\n";
if (numberofscoops == 5) {
cout << "Enter flavor 1: ";
cin >> flav1;
cout << "Enter flavor 2: ";
cin >> flav2;
cout << "Enter flavor 3: ";
cin >> flav3;
cout << "Enter flavor 4: ";
cin >> flav4;
cout << "Enter flavor 5: ";
cin >> flav5;
cout << " ( " << flav1 << " )/" << endl;
cout << " ( " << flav2 << " )" << endl;
cout << " ( " << flav3 << " )" << endl;
cout << " ( " << flav4 << " )" << endl;
cout << " ( " << flav5 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
if (numberofscoops == 4) {
cout << "Enter flavor 1: ";
cin >> flav1;
cout << "Enter flavor 2: ";
cin >> flav2;
cout << "Enter flavor 3: ";
cin >> flav3;
cout << "Enter flavor 4: ";
cin >> flav4;
cout << " ( " << flav1 << " )" << endl;
cout << " ( " << flav2 << " )" << endl;
cout << " ( " << flav3 << " )" << endl;
cout << " ( " << flav4 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
if (numberofscoops == 3) {
cout << "Enter flavor 1: ";
cin >> flav1;
cout << "Enter flavor 2: ";
cin >> flav2;
cout << "Enter flavor 3: ";
cin >> flav3;
cout << " ( " << flav1 << " )" << endl;
cout << " ( " << flav2 << " )" << endl;
cout << " ( " << flav3 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
if (numberofscoops == 2) {
cout << "Enter flavor 1: ";
cin >> flav1;
cout << "Enter flavor 2: ";
cin >> flav2;
cout << " ( " << flav1 << " )" << endl;
cout << " ( " << flav2 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
if (numberofscoops == 1) {
cout << "Enter a flavor: ";
cin >> flav1;
cout << " ( " << flav1 << " )" << endl;
cout << " \\"
<< " /" << endl << " |" << endl;
}
}
price(numcones, numberofscoops);
}
int main() {
int numberofcones;
int numberofscoops;
welcome();
cout << "How many cones would you like?(10 max) ";
cin >> numberofcones;
checkcones(numberofcones);
while (checkcones(numberofcones) == false) {
cout << "You are not allowed to buy more than 10 cones and you cannot "
"buy less than one cone. Please try again.\n";
cout << "How many cones would you like?(10 max): ";
cin >> numberofcones;
checkcones(numberofcones);
}
cout << "You are buying " << numberofcones << " ice cream cones.\n";
buildcone(numberofcones);
}
Start by changing the return value of price() to float, or the function won't be able to return the proper cost. Also, since cones is not used to compute the cost of the purchase, we don't it as a parameter:
float price(int numberofscoops)
{
float total_cost = 0.0f;
if (numberofscoops == 1) {
total_cost = 2.0f;
}
else if (numberofscoops == 2) {
total_cost = 3.0f;
}
else if (numberofscoops > 2) {
total_cost = 5.0f + ((numberofscoops-2) * 0.75f);
}
return total_cost;
}
You code could have other problems, but I think these changes will let you continue to debug and fix the code on your own.
Your while() loop is flawed. Comment your call to checkcones() as shown below. You're already calling checkcones() as the conditional in your while(), no need to evaluate again as this will sent you into a perma-loop. You've got two of these while() statements that I could see, you'll want to comment out both.
while ( checkcones( numberofcones ) == false )
{
cout << "You are not allowed to buy more than 10 cones and you cannot buy less than one cone. Please try again.\n";
cout << "How many cones would you like?(10 max): ";
cin >> numberofcones;
// THIS LINE IS THE PROBLEM :)
// checkcones(numberofcones);
}
After this fix, your program begins to work but the pricing fails. You should be able to figure that out with the answer given above.
I would also see if you can figure out how to implement a c++ class with members and methods as your current approach is very "c" like. Happy coding! :)