Math tutor program troubles - c++

Hello once again stack overflow users! I have a new program, and have once again ran into a bit of a problem I cannot figure out! I wrote a program, math tutor program, which is practically finished, just that there are a few things I cannot figure out. In the program, there is a void function that checks the answers (will display if user input is correct or incorrect) but I cant seem to get it to work. When I have it in my doOneSet void function (does exactly one set or problems) it seems to only display "incorrect" even though the answer is correct? I cant seem to figure out what I did wrong or what is missing. Any type of help/tips/references is appreciated. Thank you!
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void getProbsPerSet (int& numProbs);
void printHeader (/*in*/ char problemType);
void getMaxNum(/* out */int& maxNum);
void generateOperands(int& num1, int& num2, int maxNum);
void checkAnswer (/* in */int num1,/* in */ int num2, /*out*/ int& answer);
void calcCorrectAnswer(/* in */ char problemType,/* in */ int num1,/* in */int num2, /*inout*/ int& answer);
void doOneProblem (char problemType, int maxNum);
void doOneSet (char problemType, int probsPerSet, int&);
void printReport (/* in */ int probsPerSet, int& set1Correct, /* in */int& set2Correct, /* in */int& set3Correct);
int main ()
{
int set1Correct, set2Correct, set3Correct, probsPerSet, maxNum;
srand(time(0));
getProbsPerSet (probsPerSet);
cout << endl;
doOneSet ('+', probsPerSet, set1Correct);
cout << endl;
doOneSet ('-', probsPerSet, set2Correct);
cout << endl;
doOneSet ('*', probsPerSet, set3Correct);
cout << endl;
return 0;
}
void getProbsPerSet (int& numProbs)
{
cout << "Enter problems per set: ";
cin >> numProbs;
cout << endl;
while (numProbs < 3 || numProbs > 10)
{
cout << endl;
cout << "Please stay between 3 and 10. Thank you!";
cout << endl;
cout << endl;
cout << "Enter problems per set: ";
cin >> numProbs;
cout << endl;
}
}
void printHeader (/*in*/ char problemType)
{
switch(problemType)
{
case '+': cout << endl;
cout << "Set # 1" << endl;
cout << "----------" << endl;
break;
case '-': cout << endl;
cout << "Set # 2" << endl;
cout << "----------" << endl;
break;
case '*': cout << endl;
cout << "Set # 3" << endl;
cout << " ----------" << endl;
break;
}
}
void doOneProblem (char problemType, int maxNum)
{
int num1,num2,answer;
generateOperands(num1, num2, maxNum);
switch (problemType)
{
case '+' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
case '-' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
case '*' : cout << num1 << problemType << num2 << " = ";
cin >> answer;
break;
}
}
void doOneSet (char problemType, int probsPerSet, int& answer)
{
int num1, num2, numProbs, maxNum;
bool isCorrect;
printHeader(problemType);
getMaxNum(maxNum);
for (int count = 0; count < probsPerSet; count++)
{
generateOperands(num1, num2, maxNum);
doOneProblem (problemType, maxNum);
calcCorrectAnswer(problemType, num1, num2, answer);
checkAnswer (num1, num2, answer);
}
}
void generateOperands(int& num1, int& num2, int maxNum)
{
num1 = 1 + rand() % maxNum;
num2 = 1 + rand() % maxNum;
}
void getMaxNum(/*out*/ int& maxNum)
{
cout << "What is the maximum number for this set?: ";
cin >> maxNum;
}
void checkAnswer (int num1, int num2, /*out*/ int& answer)
{
bool isCorrect;
if (answer == isCorrect)
{
cout << endl;
cout << "Correct!" << endl;
cout << endl;
}
else
{
cout << endl;
cout << "Incorrect!" << endl;
cout << endl;
}
}
void calcCorrectAnswer(/* in */ char problemType,/* in */ int num1,/* in */int num2, /*inout*/ int& answer)
{
bool isCorrect;
switch (problemType)
{
case '+' : isCorrect = num1 + num2;
break;
case '-' : isCorrect = num1 - num2;
break;
case '*' : isCorrect = num1 * num2;
break;
}
}
void printReport (/* in */ int probsPerSet, int& set1Correct, /*in*/ int& set2Correct, /*in*/ int& set3Correct)
{
int set1Percent = 0, set2Percent = 0, set3Percent = 0;
int total, complete;
int numcorrect = 1;
total = set1Correct + set2Correct + set3Correct;
complete = probsPerSet + probsPerSet + probsPerSet;
set1Percent = (100 * set1Correct) / probsPerSet;
set2Percent = (100 * set2Correct) / probsPerSet;
set3Percent = (100 * set3Correct) / probsPerSet;
cout << endl;
cout << "Set #1 : You got " << set1Correct << " correct out of " << probsPerSet << " for " << set1Percent << "%" << endl;
cout << "Set #2 : You got " << set2Correct << " correct out of " << probsPerSet << " for " << set2Percent << "%" << endl;
cout << "Set #3 : You got " << set3Correct << " correct out of " << probsPerSet << " for " << set3Percent << "%" << endl;
cout << endl;
cout << "Overall you got " << total << " out of " << complete << endl;;
}

The problem is your bool isCorrect;. Both of them. 😎
So, in one function, calcCorrectAnswer, you declare this variable, then set it according to the logic of your requirements. Fine.
Then in another function, checkAnswer, you declare it again, then compare it to true/false to choose which output to produce.
But these are different variables. Despite sharing a name, they are scoped to the function they're in, so setting one has no effect on the other. The one in checkAnswer is uninitialised and never takes a value, so your program has undefined behaviour.
You could return your boolean from calcCorrectAnswer and pass it as an argument to checkAnswer. Or you could just merge those two functions; there doesn't seem to be a big reason to keep them separate.

Related

"0" appearing after function is completed in C++

// This program is able take two variables`
// and apply Auto increment or decrement`
// based on the user's input and by calling a function
#include <iostream>
using namespace std;
int inc (int, int); // Increment function prototype
int dec (int, int); // Decrement function prototype
int main ()
{
int num1, num2;
char operation = ' ', I, D;
cout << "Enter the first variable: ";
cin >> num1;
cout << "Enter the second variable: ";
cin >> num2;
cout << endl;
cout << "Do you want Auto increment, decrement or both? (Type 'I', 'D' or 'B'): ";
cin >> operation;
if (operation == 'I') {
cout << inc(num1,num2);
}
else if (operation == 'D') {
cout << dec(num1,num2);
}
else if (operation == 'B') {
cout << inc(num1,num2);
cout << endl;
cout << dec(num1,num2);
}
else {
cout << "Error please enter 'I', 'D' or 'B' as a option" << endl;
}
return 0;
}
int inc (int num1, int num2) {
num1++; num2++;
cout << "Number 1 ++ is: " << num1 << endl;
cout << "Number 2 ++ is: " << num2 << endl;
return 0;
}
int dec (int num1, int num2) {
--num1; --num2;
cout << "Number 1 -- is: " << num1 << endl;
cout << "Number 2 -- is: " << num2 << endl;
return 0;
}
I just started taking Fundamentals of programming I at college and i have this assignment and this 0 keeps appearing after the function has completed
This happens because your inc and dec print stuff, but also return an int. You then proceed to print the return value, on these lines:
cout << inc(num1,num2);
and
cout << dec(num1,num2);
.
You can safely remove these cout << prefixes, and probably the entire return value, as it does not seem necessary to output your resuls (that happens in inc and dec).
int inc (int &num1, int &num2)
int dec (int &num1, int &num2)
Don't forget the ampersand to modify globalvariables
if (operation == 'I') {
cout << inc(num1,num2);
}
else if (operation == 'D') {
cout << dec(num1,num2);
}
else if (operation == 'B') {
cout << inc(num1,num2);
cout << endl;
cout << dec(num1,num2);
}
In this section don't use cout. The function is returning 0 and you are printing it using cout << dec(num1,num2);.
Just call the function as you are printing the values inside the function.
if (operation == 'I') {
inc(num1,num2);
}
else if (operation == 'D') {
dec(num1,num2);
}
else if (operation == 'B') {
inc(num1,num2);
cout << endl;
dec(num1,num2);
}
And also as if you want to modify num1 and num2 inside the functions so that the variables declared in main function is modified also, then you have to pass by reference like:
int inc (int &num1, int &num2) {
num1++; num2++;
cout << "Number 1 ++ is: " << num1 << endl;
cout << "Number 2 ++ is: " << num2 << endl;
return 0;
}
int dec (int &num1, int &num2) {
--num1; --num2;
cout << "Number 1 -- is: " << num1 << endl;
cout << "Number 2 -- is: " << num2 << endl;
return 0;
}

Switch statements will not execute

I have an assignment here that I've been working on for the past few hours and have been met with a problem. Whenever I compile and run the program in VS Code it throws me into an infinite loop where the text of the "menu" is printed repeatedly. I imagine this has something to do with the for(;;){ loop at the beginning of the menu.
I've deleted the for(;;){ statement at the beginning of the menu, and the continuous scrolling stopped, but I was unable to input any numbers (cases) and the program, essentially, just printed the menu and that was the end.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Student {
string name;
float GPA;
public:
string getName() const
{
return name;
}
float getGPA() const
{
return GPA;
}
void setName(string Name)
{
name = Name;
}
void setGPA(float gpa)
{
GPA = gpa;
}
Student(const string& name, float gpa)
: name(name)
, GPA(gpa)
{
}
Student()
{
}
void printDetails(Student s[], int n)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n; i++) {
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
float calcAverageGPA(Student s[], int n)
{
float avg = 0;
float sum = 0;
for (int i = 0; i <= n; i++) {
sum += s[i].getGPA();
}
avg = sum / n;
return avg;
}
float getGPAbyName(Student s[], int n, string name)
{
for (int i = 0; i <= n - 1; i++) {
if (s[i].getName() == name)
return s[i].getGPA();
}
return -1;
}
void showListByGPA(Student s[], int n, float gpa)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n - 1; i++) {
if (s[i].getGPA() > gpa)
;
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
};
int main()
{
int n = 0;
int ch;
Student s[50];
string name;
float GPA;
float avg = 0;
cout << "======================" << endl;
cout << "(1): Add a student" << endl;
cout << "(2): Print the details of a student" << endl;
cout << "(3): Get the GPA of a Student by name." << endl;
cout << "(4): Get names of students based on GPA." << endl;
cout << "(6): Quit the program." << endl;
cout << "Enter your option" << endl;
switch (ch) {
case '1':
cout << "\nEnter student's name" << endl;
cin >> name;
cout << "Enter GPA" << endl;
cin >> GPA;
s[n] = Student(name, GPA);
n++;
break;
case '2':
s[0].printDetails(s, n);
break;
case '3':
cout << "\nEnter the name of a student" << endl;
cin >> name;
GPA = s[0].getGPAbyName(s, n, name);
if (GPA == -1) {
cout << "\nStudent not found!" << endl;
}
else
cout << "\nGPA is: " << endl;
break;
case '4':
cout << "\nEnter GPA: " << endl;
cin >> GPA;
s[0].showListByGPA(s, n, GPA);
break;
case '5':
avg = s[0].calcAverageGPA(s, n);
cout << "\nAverage GPA: " << avg << endl;
break;
case '6':
exit(0);
}
}
I suspect the problem resides in main(). I included the prior blocks of the program in case they were necessary to provide any suggestions.
You obviously want to read in "ch".
You've also made this an int, and don't zero-initialize, which can cause some undefined behaviour if you don't set it beforehand.
The switch case should be
switch(X){
case 1:
// Code
break;
}
etc..
The difference is "1" or 1. It evaluates an enumeration value, instead of strings.
For safety: you might want to add a case default, which is common practice.

C++ number manipulator programer

I'm a beginner at C++ and function,
Been getting the error "linker command failed with exit code 1" wondering anyone could give me some insight on how to resolve this problem, and on my overall code organization. Thank you very much for your time and opinion on this matter :)
ignore the below statement
(Due to lack of space I had to remove the #include statements which included the following iostream, iomanip, string and cmath).
#include<iostream>
#include<iomanip>
#include<string>
#include<cmath>
void header();
double number();
int menu();
void seeMenu();
void processChoice();
void negPos();
int squareRoot();
void evenOdd();
void numOfDigits();
void digitAtPos();
using namespace std;
int main()
{
int choice = 0;
header();
number();
menu();
seeMenu();
processChoice();
while (choice != 0) {
processChoice();}
return 0;
}
void header(){
cout << "Number Manipulator"<< endl; }
double number() {
double num;
cout << "Enter a number to continue: ";
cin >> num;
return num; }
int menu(){
cout << "\nHere are your choices:";
cout << endl << setw(29) << "1) Is it even or odd?";
cout << endl << setw(38) << "2) Is it positive or negative?";
cout << endl << setw(49) << "3) What is the square root?";
cout << endl << setw(41) << "4) How many digits in the number?";
cout << endl << setw(54) << "5) What is the digit at a particular location?";
cout << endl << setw(19) << "0) To Quit.";
}
int showMenu() {
int choice;
cout << endl << endl <<"Enter your choice: ";
cin >> choice;
return choice; }
void processChoice(int choice) {
switch (choice) {
case 1: squareRoot();
break;
case 2: evenOdd();
break;
case 3: negPos();
break;
case 4: numOfDigits();
break;
case 5: digitAtPos();
break;
default:
cout << "This is not a valid choice. Please try again!";
showMenu();
break; }}
void negPos(int num) {
if (num > 0) cout << "Number is Positive"<< endl;
if (num < 0) cout << "Number is Negative"<< endl;
if (num == 0) cout << "Number is Zero"<< endl; }
void evenOdd(int num) {
if (num%2 == 0) cout << "Number is even";
else cout << "Number is odd"; }
void squareRoot(int num) {
int numSqrt;
numSqrt=sqrt(num);
cout << "Square root of " << num << " is " << numSqrt; }
void numOfDigits(int num) {
int numDigits=0;
do {
num /= 10;
numDigits++;
} while(num);
cout << "The number of digits in " << num << " is " << numDigits; }
void digitAtPos(int num) {
int pos;
cout << "What Position?: ";
cin >> pos; }
//need to be completed
While quickly looking over your code, I noticed that the function processMenuChoice is declared as void processMenuChoice(), but it is defined as void processMenuChoice(int choice). And since the function needs that paramater, you need to change your while loop to
processMenuChoice(choice);
while(choice != 0)
{
processMenuChoice(choice);
}
Here is the fix to make your code work. Note, there are some other issues that you need to fix.
Hint: in void squareRoot(int num), the result is an integer...
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
void displayHeader();
double getNumber();
int showMenu();
void menu();
void processMenuChoice(int choice, int num);
void isPosNeg(int num);
void squareRoot(int num);
void isOddEven(int num);
void findNumDigits(int num);
void findDigitAtPosition(int num);
using namespace std;
int main()
{
int choice = 0;
displayHeader();
int num = getNumber();
menu();
choice = showMenu();
while (choice != 0) {
processMenuChoice(choice, num);
choice = showMenu();
}
return 0;
}
void displayHeader(){
cout << "Number Manipulator\n"; }
double getNumber() {
double num;
cout << "Enter a number to continue: ";
cin >> num;
return num; }
void menu(){
cout << "\nHere are your choices:";
cout << endl << setw(29) << "1) Is it even or odd?";
cout << endl << setw(38) << "2) Is it positive or negative?";
cout << endl << setw(49) << "3) What is the square root?";
cout << endl << setw(41) << "4) How many digits in the number?";
cout << endl << setw(54) << "5) What is the digit at a particular location?";
cout << endl << setw(19) << "0) To Quit.";
}
int showMenu() {
int choice;
cout << "\n\nEnter your choice: ";
cin >> choice;
return choice; }
void processMenuChoice(int choice, int num) {
switch (choice) {
case 1: isPosNeg(num);
break;
case 2: isOddEven(num);
break;
case 3: squareRoot(num);
break;
case 4: findNumDigits(num);
break;
case 5: findDigitAtPosition(num);
break;
default:
cout << "This is not a valid choice. Please try again!";
showMenu();
break; }}
void isPosNeg(int num) {
if (num > 0) cout << "Number is Positive\n";
if (num < 0) cout << "Number is Negative\n";
if (num == 0) cout << "Number is Zero\n"; }
void isOddEven(int num) {
if (num%2 == 0) cout << "Number is even";
else cout << "Number is odd"; }
void squareRoot(int num) {
int numSqrt;
numSqrt=sqrt(num);
cout << "Square root of " << num << " is " << numSqrt; }
void findNumDigits(int num) {
int numDigits=0;
do {
num /= 10;
numDigits++;
} while(num);
cout << "The number of digits in " << num << " is " << numDigits; }
void findDigitAtPosition(int num) {
int pos;
cout << "What Position?: ";
cin >> pos; }
//need to be completed

Arrays Lose Value Upon Return (Inventory/Menu Program) C++

So for the most part I understand what I did wrong, the issue is I don't know how to fix it.
Goal: This is a store management system that must include a menu and inventory management functions that can be manipulated. To do this I used arrays to add the store's items, their descriptions, and their quantities. All the arrays are partially filled to the third element and have a max value of ten elements.
Issue: When the program is run the first time it works and the user can see their inventory, description and quantity. However when they exit to the menu and come BACK to inventory, everything past the third element is cleared. This is due to the declarations initializing the arrays past the third element to 0. How do I fix this to guarantee the user has their inventory saved and can view it upon return?
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
//declarations
int mainMenu(); //done
void inventoryMgmt();
void addInv(); //working on
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray);
void customerReciept(); //done
void calculatePrice(); //done
void exit(); //done
const double massTax = 0.0625;
//main
int main() {
int choice;
bool repeat = true;
while (repeat = true) {
choice = mainMenu();
switch (choice) {
case 1:
customerReciept();
break;
case 2:
inventoryMgmt();
break;
//case 3:
//itemSearcher();
//break;
case 4:
exit();
repeat = false;
break;
}
}
return 0;
}
//main menu function ***done
int mainMenu() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Main Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Customer Reciept" << endl;
cout << "\t\t\t\t\t\t 2. Inventory Management" << endl;
cout << "\t\t\t\t\t\t 3. Item Search" << endl;
cout << "\t\t\t\t\t\t 4. Exit" << endl << endl;
int choice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> choice;
while (choice < 1 || choice > 4) {
cout << "\t\t\t\t\t Incorrect Selection Please Select Again: ";
cin >> choice;
}
return choice;
}
//customer reciept function **done
void customerReciept() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t\t Receipt Menu: " << endl;
cout << "\t\t\t\t\t\t 1. Calculate Receipt" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
int recieptChoice;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> recieptChoice;
while (recieptChoice < 1 || recieptChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> recieptChoice;
}
if (recieptChoice == 1) {
calculatePrice();
}
}
void calculatePrice() {
double cost;
double taxAmount;
int numOfItems;
double finalCost = 0;
char tax;
int i;
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store: Customer Reciept " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "How many items were purchased?: ";
cin >> numOfItems;
for (i = 0; i < numOfItems; i++) {
cout << "What did item " << i + 1 << " cost? $";
cin >> cost;
cout << "Is this item taxable? (y/n):";
cin >> tax;
if (tax == 'y' || tax == 'Y') {
taxAmount = (cost * massTax);
cost = taxAmount + cost;
finalCost = cost + finalCost;
}
else {
finalCost = cost + finalCost;
}
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << "This customer's total is $" << finalCost << endl;
}
void inventoryMgmt() {
int invChoice;
cout << "\n\n\t\t\t\t\t Welcome to Inventory Management " << endl;
cout << "\t\t\t\t ______________________________________________ \n\n";
cout << "\t\t\t\t\t Inventory Settings: " << endl;
cout << "\t\t\t\t\t\t 1. Add/View & Edit/Delete Inventory" << endl;
cout << "\t\t\t\t\t\t 2. Return to Main" << endl;
cout << "\t\t\t\t\t\t Where do you need to go?: ";
cin >> invChoice;
cout << endl << endl;
while (invChoice < 1 || invChoice > 2) {
cout << "Invalid Selection Please Choose Again: ";
cin >> invChoice;
}
if (invChoice == 1) {
addInv();
}
if (invChoice == 2) {
//edit/delete();
}
}
void addInv() {
//so when this is called, everything is initialized to 0 which makes it wipe the memory
//when the user comes back to it from the menu.
const int description = 20; //this allows a short description for each item
const int counter = 10; //slots of inventory allowed
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "Hot Drinks", "Cold Drinks", "Books"};
string descriptionArray[description] = { "Coffee, Tea etc", "Water, juice, etc", "Texts, notebook, etc"};
char addChoice;
int destination;
cout << "\t\t\t\t\t\t 1. Add/View" << endl;
cout << "\t\t\t\t\t\t 2. Edit/Delete" << endl;
cout << "\t\t\t\t\t\t 3. Exit to Main" << endl;
cout << "\t\t\t\t\t\t Where would you like to go?: " << endl;
cin >> destination;
while (destination < 1 || destination > 3) {
cout << "Invalid Selection, Please Select Again: ";
cin >> destination;
}
if (destination == 1) {
cout << "Would you like to add an item? (y/n): ";
cin >> addChoice;
int i = 3; //these two are initialized to three to ensure that the store
int ii = 3; //will always have hot drinks, cold drinks and books as options
while (addChoice == 'y' && i < counter) {
cout << "What would you like to add?: ";
cin >> itemArray[i];
cout << "You have added \"" << itemArray[i] << "\" to the inventory\n";
cout << "Please Provide a Brief Description: ";
cin.ignore();
getline(cin, descriptionArray[ii]);
cout << "You've described \"" << itemArray[i] << "\" as \"" << descriptionArray[i] << "\"" << endl;
cout << "What is the quantity of " << itemArray[i] << " in stock?";
cin >> quantity[i];
cout << "Would you like to add another item?";
cin >> addChoice;
i++;
ii++;
if (i > counter) {
cout << "**INVENTORY LIMIT REACHED*** ";
}
}
invView(itemArray, 10, descriptionArray, 10, quantity, 10); //working on this. //so use this for view, edit, and delete.
}
}
void invView(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) { //add quantity
int i = 0;
int ii = 0;
int iii = 0;
cout << "Your inventory consists of: ";
while (i < sizeofArray && x[i] != "" && ii < secondArray && y[i] != "" && iii < thirdArray) {
cout << x[i] << " - " << y[i] << " | Quantity: " << z[i] << endl;
i++;
ii++;
}
}
void editor(string x[], int sizeofArray, string y[], int secondArray, int z[], int thirdArray) {
cout << "Which item would you like to edit?";
}
void exit() {
cout << "\n\n\t\t\t\t Welcome to the Massasoit Store Management System " << endl;
cout << "\t\t\t\t ________________________________________________ \n\n";
cout << "\t\t\t\t Thank you for using the Massasoit Store Management System" << endl;
exit(1);
}
I included the entire code in case it was needed. The issues are centered around the inventoryMgmt() and addInv() functions.
Thanks in advance for any help!
In theaddInv() all the arrays are local. Once that function is done executing, all local variables are freed up thus resulting in your deletion. Try place them outside your addInv() function:
int main(){
int quantity[10] = {10, 15, 45};
string itemArray[counter] = { "..."};
string descriptionArray[description] = { "..."};
void addInv() {...}
}

Calculator in C++ with different types and operations to choose

I'm about to create simple calculator in C++. It should allow user to chose type and operations on two typed numbers. So at first, user have to choose number type from list(which shows different types like int, double, short etc.). After that it should allow you to write two numbers of type that you selected before. Then at the end you need to decide what operation would like to do with this numbers (+,-,/,*). My problem is that I don't know how to take those inputted numbers from methods to main() so i could make operations on that.
#include <iostream>
using namespace std;
int integer()
{
int number1;
int number2;
cout << "First number: " << endl;
cin >> number1;
cout << "Second number: " << endl;
cin >> number2;
}
double doubl()
{
double number1;
double number2;
cout << "First number: " << endl;
cin >> number1;
cout << "Second number: " << endl;
cin >> number2;
}
int main()
{
cout << "Type to choose:" << endl;
cout << "1. int" << endl;
cout << "2. double" << endl;
int choosed;
cin >> choosed;
switch(choosed) {
case 1:
integer();
break;
case 2:
doubl();
break;
default:
cout << "Error" << endl;
break;
}
cout << "What operation would like to do on this numbers?" << endl;
cout << "1. +" << endl;
cout << "2. -" << endl;
cout << "3. *" << endl;
cout << "4. /" << endl;
int result;
switch(result){ //at this point i don't know how to invoke those numbers from methods
case 1:
}
cin.get();
}
Thanks!
you can return a std::pair from your functions
std::pair<double,double> doubl()
{
...
return std::make_pair(number1,number2);
}
Then use it
std::pair<double,double> nums = doubl();
double res = nums.first <operation> nums.second;
When you feel comfortable with this I would recommend you to look into using templates to create your reading functions.
Here's one way to do it in C++. Basically, you have to store your answers in a variable in main() and you can use a flag to tell you whether it is a int or a double variable and operation.
#include <iostream>
using namespace std;
template<class T>
class numbers
{
private:
T num1;
T num2;
public:
numbers() : num1(0), num2(0) {}
void setvalues(T n1, T n2) {num1 = n1; num2 = n2;}
T add() {return num1 + num2;}
T subtract() {return num1 - num2;}
T multiply() {return num1 * num2;}
T divide() {return (num2 != 0) ? num1 / num2 : 0;}
};
void integer(numbers<int>& numo)
{
int number1;
int number2;
cout << "First number: " << endl;
cin >> number1;
cout << "Second number: " << endl;
cin >> number2;
numo.setvalues(number1, number2);
}
void doubl(numbers<double>& numo)
{
double number1;
double number2;
cout << "First number: " << endl;
cin >> number1;
cout << "Second number: " << endl;
cin >> number2;
numo.setvalues(number1, number2);
}
int main()
{
cout << "Type to choose:" << endl;
cout << "1. int" << endl;
cout << "2. double" << endl;
int choosed;
cin >> choosed;
numbers<int> num_int;
numbers<double> num_dbl;
int typeOfVal = 0; // 1 for integer, 2 for double
switch(choosed) {
case 1:
integer(num_int);
typeOfVal = 1;
break;
case 2:
doubl(num_dbl);
typeOfVal = 2;
break;
default:
cout << "Error" << endl;
return 1;
}
int typeOfOp = 0;
cout << "What operation would like to do on this numbers?" << endl;
cout << "1. +" << endl;
cout << "2. -" << endl;
cout << "3. *" << endl;
cout << "4. /" << endl;
cin >> typeOfOp;
int resint; //result for int
double resdbl; // result for double
switch(typeOfOp){
case 1:
if (typeOfVal == 1) resint = num_int.add(); else resdbl = num_dbl.add();
break;
case 2:
if (typeOfVal == 1) resint = num_int.subtract(); else resdbl = num_dbl.subtract();
break;
case 3:
if (typeOfVal == 1) resint = num_int.multiply(); else resdbl = num_dbl.multiply();
break;
case 4:
if (typeOfVal == 1) resint = num_int.divide(); else resdbl = num_dbl.divide();
default:
cout << "Error" << endl;
return 1;
}
cout << "The answer:" << endl;
if (typeOfVal == 1) cout << resint << endl;
else cout << resdbl << endl;
cin.get();
return 0;
}
If I were you I would have written the code like this: I think it is more standard than any other above code.
#include<iostream>
#include<string>
using namespace std;
const string EXIT = "-1";
void add(float num1, float num2)
{
cout<<"Result is: "<< num1 + num2 <<endl;
}
void subtract(float num1, float num2)
{
cout<<"Result is: "<< num1 - num2 <<endl;
}
void multiply(float num1, float num2)
{
cout<<"Result is: "<< num1 * num2 <<endl;
}
void divide(float numerator, float denominator)
{
if (denominator != 0)
cout<<"Result is: "<< numerator / denominator <<endl;
else
cout<<"You can not divide by denominator\n";
}
void modulus(float num1, float num2)
{
cout<<"Result is: "<< (int)num1 % (int)num2 <<endl;
}
int main(void)
{
string mathematicalOperation;
float num1, num2;
char operatorSign;
cout << "Please enter an arithmetic expression (-1 to Exit)\n";
cin >> mathematicalOperation;
//search for operator sign and perform calculation
while(mathematicalOperation.compare(EXIT))
{
int getFirstDigitIndex = mathematicalOperation.find_first_of("0123456789");
int operatorSignIndex = mathematicalOperation.find_first_of("+-*/%", getFirstDigitIndex);
if (operatorSignIndex != -1)
{
operatorSign = mathematicalOperation.at(operatorSignIndex);
string firstNumber = mathematicalOperation.substr(0,operatorSignIndex);
string secondNumber = mathematicalOperation.substr(operatorSignIndex + 1);
//convert numbers from string to float
num1 = (float)atof(firstNumber.c_str());
num2 = (float)atof(secondNumber.c_str());
switch(operatorSign)
{
case '+':
add(num1,num2);
break;
case '-':
subtract(num1,num2);
break;
case '*':
multiply(num1,num2);
break;
case '/':
divide(num1,num2);
break;
case '%':
modulus(num1,num2);
break;
}
}
cout<<"Please Enter Another Expression or Enter -1 to Exit:\n";
cin>>mathematicalOperation;
}
cout<<"SEE YOU LATER!\n";
return 0;
}