Function that returns input?

Hey guys, really quick question :) I am trying to make a basic calculator and am trying to produce a function which displays the main menu, takes user input and then returns the user input. With this returned input I was then hoping to use if statements. This is what I have so far, but it doesnt seem to be working. Any help would be appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream>

using namespace std;


//Menu Function
int CalculatioOptions(int answer){

     cout << "What would you like to do: \n";
     cout << "1. Addition \n";
     cout << "2. Subtraction \n";
     cout << "3. Division \n";
     cout << "4. Multiplication \n";

     cin >> answer;
     
     return answer;

}

int main(){


int useroption;


CalculatioOptions(useroption);

if(useroption == 1){ ... etc.

return 0;

}

For some reason when i press 1 the rest of the program doesnt work. I have tried couting the answer variable in the function and it works then... 
What function CalculatioOptions is doing exactly?
Think for a while.

You wanted to do this:

1
2
3
//code
useroption = CalculatioOptions(/*well, anything could be here*/)
//code 


If you want to change some variable by passing it as argument of a function, you should consider using pointers( http://www.cplusplus.com/doc/tutorial/pointers/ ) or reference.

Or maybe you didn't know that function takes a copy of argument instead of actual object?

Then I suggest you reading this:

http://www.cplusplus.com/doc/tutorial/functions/

And make sure you understand functions.
Last edited on
Firstly, I'm pretty sure it would be better to use a double and anyways I hate inputing as ints/doubles I like to do strings so you can validate if it is a letter, number, space, ect...and then convert to a number if it is.
and secondly it should be
useroption = calculationoption();

I would also get rid of the (int answer) paramater unless you are going to do something like this before calling the function
1
2
 int useroption = 0;
useroption = calculationoption(useroption);


oh and another way to do it which I prefer is using a reference like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <stdlib.h>
void caclulationoption(unsigned double &a)
{
string answer, error;
do {
 error = "false";
 cout << "something: " << flush;
 getline(cin, answer);
 for(unsigned int i = 0; i<answer.size(); i++) if(isalpha(answer[i])) error = "true";
} while(error == "true");

a = (unsigned double)atoi(answer.c_str());
}
int main()
{
 unsigned double option;
 calculationoption(option);
}
Last edited on
@giblit

What are you talking about?

Can you explain what an unsigned double is? Do you know what floating point numbers are in general?

Your code & most of the things you said make no sense at all. Try compiling your code before posting it.


@jefw123

Use a switch to process the menu options. Provide a default clause to deal with bad input, and an option to quit the program.

Hope all goes well.

I think you would want the if statements in the function. You are trying to ask the user which operation that he/she would want to do correct? I would suggest switch statement for that.
I used to program quite a bit in c++ and only just got back into it. Hence, why I am rusty with things like switch statements :P

Just want to say a huge thankyou to all who responded - I managed to fix the issue I was having :)

@MatthewRock

Function CalculatiOptions is basically the main menu of my calculator program. It takes the user input (their choice on whether they want addition, subtraction etc.) and uses this input for the if statements to determine which function needs to be activated in order to calculate the result.

Yes! That is exactly what I needed, so a HUGE thankyou. I am still very new to c++ so I will read the two articles that you posted. I have already flicked through them and they look very informative. You have been a great help :D

@giblit

Firstly thank you for replying to my thread. I am still VERY new to c++, so I do not know what a double is. Is it where you allow decimals? Because if so, I dont think I would need that for the main menu aha :) Surely I need the int answer so that the function can return what the user inputted so that this value can be used with useroption? Really sorry, but i dont really understand your code... :/

@TheIdeasMan

It is good to see that someone else was confused by giblit too!! I was getting worried there ha.

I tried adding and else clause saying WRONG INPUT!! but it seems to come up after the user has done their sums? Also, next I would like an option for the user to go back to the main menu, but I am not sure how to implement that yet. A nod in the right direction regarding this aspect would be great! Thanks - likewise with you!

@crimsonzero2

Is it bad practice to use the if statements as I am at the moment?
Ok, thankyou very much, I shall look into switch statements.

To All:

Here is what I have ended up with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#include <iostream>

using namespace std;


//Menu Function
int CalculatioOptions(int answer){

     cout << "What would you like to do: \n";
     cout << "1. Addition \n";
     cout << "2. Subtraction \n";
     cout << "3. Division \n";
     cout << "4. Multiplication \n";

     cin >> answer;

     return answer;

}



//Addition Function
class Addition{


     public:

         void enterNumber(){
             int x;
             int y;
         cout << "Please enter two numbers: \n";
         cout << "First Number: ";
         cin >> x;
         cout << endl;
         cout << "Second Number: ";
         cin >> y;
         cout << endl;

         int answer = x + y;
         cout << "The answer is: ";
         cout << answer;

}
};

class Subtraction{


     public:

         void enterNumber(){
         int x;
         int y;


         cout << "Please enter two numbers: \n";
         cout << "First Number: ";
         cin >> x;
         cout << endl;
         cout << "Second Number: ";
         cin >> y;
         cout << endl;

           int answer = x - y;
           cout << "The answer is: ";
           cout << answer;
           cout << endl;

}


};

class Division{


     public:

         void enterNumber(){
         int x;
         int y;

         cout << "Please enter two numbers: \n";
         cout << "First Number: ";
         cin >> x;
         cout << endl;
         cout << "Second Number: ";
         cin >> y;
         cout << endl;

         int answer = x / y;
         cout << "The answer is: ";
          cout << answer;
          cout << endl;

          int remainder = x % y;
          cout << "And the remainder is: ";
          cout << remainder;
          cout << endl;
}


};

class Multiplication{


     public:

         void enterNumber(){
         int x;
         int y;

         cout << "Please enter two numbers: \n";
         cout << "First Number: ";
         cin >> x;
         cout << endl;
         cout << "Second Number: ";
         cin >> y;
         cout << endl;

         int answer = x / y;
         cout << "The answer is: ";



         cout << answer;
         cout << endl;

}

};




int main(){

//Defining Variables
int useroption;



//Defining Classes
Addition Additionclass;
Subtraction SubtractionClass;
Division DivisionClass;
Multiplication MultiplicationClass;





//BEGINNING OF PROGRAM
useroption = CalculatioOptions(useroption);



if(useroption == 1){

        Additionclass.enterNumber();
}



if(useroption == 2 ){

 SubtractionClass.enterNumber();


}

if(useroption == 3 ){

 DivisionClass.enterNumber();



}

if(useroption == 4 ){

 MultiplicationClass.enterNumber();
}

return 0;


}




Please do not refrain from telling me what you think of it - such as bad practice, or what I could have made clearer etc. :)
Last edited on
It's probably a bit much to have a class for each +-*/. Just have 1 class - keep data members private, provide some constructors. Provide public functions as an interface to the class.

Getting the numbers & the operator should be common to all the functions.

Read up the tutorial on this site - it has a whole section on classes & switches etc.
to me it seems like you wanna do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main(){

int answer;

     cout << "What would you like to do: \n";
     cout << "1. Addition \n";
     cout << "2. Subtraction \n";
     cout << "3. Division \n";
     cout << "4. Multiplication \n";

     cin >> answer;

switch(answer)
{
    case '1': ..... //write code here
    case '2': .... //write code here

etc...

}


this is what i would do
@mandy012
You should either change type of answer to char or change case '1': to case 1:
closed account (3qX21hU5)
You could do this if you want to use a switch that handles whatever returns from your menu function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int CalculatioOptions(){

     cout << "What would you like to do: \n";
     cout << "1. Addition \n";
     cout << "2. Subtraction \n";
     cout << "3. Division \n";
     cout << "4. Multiplication \n";

     int answer;
     cin >> answer;

     return answer;
}

int main ()
{
    // Just call your CalculatioOptions function inside the switch.
    switch(CalculatioOptions())
    {
    case 1:
        cout << "Do addition stuff" << endl;
        break;

    case 2:
        cout << "Do Subtraction Stuff" << endl;
        break;

    // ECT....
    }
    return 0;
}


Also I agree with IdeasMan having a class for each +, - , * and / is a little bit overkill. I would go with either a class that has member functions for each of them or just have normal functions for each of them
Hey again.

First - my question about what your function is doing wasn't intended to get answer, but to make you think for a while. I didn't want an answer that says "well, it will ask something", but rather "first off, it prints a menu to user. Then, it waits for an input stored in some variable, and then it returns this input."

And looking at what you told your function is doing - you are wrong. It doesn't activate any if statements, it justs, well, prints menu and gets input. Simple as that.

And going back to topic, I think using classes( especially this way! ) is a overkill. Sometimes simple solutions are the best solutions. Of course, you could make it work with classes, but... why? @Zereo made it look good with simple switch(case). Doesn't it look better? It's easier to manage code that isn't too complicated( I prefer keeping things as simple as they can be).

And going back to what @giblit said at the beggining - when you begin programming, you just want your programs to work. Later on, when you kinda know syntax and basics, you want your programs to work well, and elimiate possible bugs, errors. In your program you assume, that user will know that input has to be an integer, and that he will not write something else. From what I remember, if you write "asd" instead of "1", your program will loop/crash. It's simply because of wrong type of variable.

If you are in very beggining of your education, you can obviousely ignore it - as I said, make things simple, so you can understand them better. Later, when you feel good enogh, you may want to improve and protect your program from invalid input - and this can be done by using character strings, and then checking if data type is valid.

Anyway; I suggest using switch(case), or if you don't want it, if statements, simple functions, and you will have your calculator in no time.

Good luck!
@The ideas man you're right I did not test my code sorry. I'm not sure exactly what I was trying to do at the time I posted it..what I meant was this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
void caclulationoption(unsigned int a)
{
    string answer[2], error;
    unsigned int num[2];
    do {
        error = "false";
        cout << "First number: " << flush;
        getline(cin, answer[0]);
        cout << "Second number: " << flush;
        getline(cin, answer[1]);
        for(unsigned int j = 0; j < 2; j++) for(unsigned int i = 0; i<answer[j].size(); i++) if(!isdigit(answer[j][i])) error = "true";
    } while(error == "true");
    num[0] = atoi(answer[0].c_str());
    num[1] = atoi(answer[1].c_str());
    switch(a){
    case 1: cout << answer[0] << " + " << answer[1] << " = " << num[0] + num[1] << flush; break;
    case 2: cout << answer[0] << " - " << answer[1] << " = " << num[0] - num[1] << flush; break;
    case 3: cout << answer[0] << " * " << answer[1] << " = " << num[0] * num[1] << flush; break;
    case 4: cout << answer[0] << " / " << answer[1] << " = " << num[0] / num[1] << flush; break;
    }
}

int main()
{
    string answer, error;
    unsigned int option;
    do {
     error = "false";
     cout << "Add - 1\nSubtract - 2\nMultiply - 3\nDivide - 4\nOption: " << flush;
     getline(cin, answer);
     for(unsigned int i = 0; i<answer.size(); i++) if(!isdigit(answer[i])) error = "true";
     option = atoi(answer.c_str());
    } while( error == "true" || option == 0 || option > 4 );
    caclulationoption(option);
}

but like matthew rock said its better to just keep it simple and easy and not complicate everything like me ( I have this thing where I try to eliminate all the bugs possible).

Oh and I have no idea why I was using unsigned double..it was meant to be unsigned int. and anyways with my method it is impossible to input a negative number so it would work with out unsigned just fine because '-
is not a digit.
Last edited on
@giblit

Compare your code to Zereo's there is no need to go to the lengths you went to - you can use cin.ignore instead. It does the same thing as your code in main. In any case the default clause in the switch should catch any bad input - the same idea as an else statement. Also it is better to use a bool type for error flags rather than a string. Always read all the reference material for the functions you use.

Einstein once said "Things should be simple, simple as possible, but no simpler"

@jefw123

Don't forget to use doubles for your numbers & check for divide by zero in the division. To do this, check the absolute value of the number is less than an arbitrary precision like 0.01 say. This is because doubles are stored as binary fractions and never exactly equal zero.
Last edited on
@TheIdeasMan
well a bool is really an int of 1 or 0 so should I use int instead of bool =p jokes
I suppose I could of used the default but I just have a habit of it checking before I do anything with it because I always see people doing
1
2
3
4
5
int input;
do { 
cout << "input a number between 1 and 9: " << flush;
cin >> input;
} while (input > 0 && input < 10);

and if you input something like 'a' or 'b' you have a large bug and bugs like that annoy me =p
giblit wrote:
well a bool is really an int of 1 or 0 so should I use int instead of bool


You had a string - how many ways are there to specify true or false with mixed case or bad spelling. Compare that to using a bool which can only be true or false. You could use int, but bool is simpler, easier & better IMO.

giblit wrote:
I suppose I could of used the default but I just have a habit of it checking before I do anything with it because I always see people doing


But I am saying there is no need to write code that does the same thing as cin.ignore there is also cin.fail etc.

What I am trying to get through to you is: Don't write C code that does the same thing as existing facilities in C++.

It just leads to overly complicated code.

Btw std::endl flushes the buffer as well.
Wow, so many responses which is great!! I will go through each of your suggestions one by one.

@TheIdeasMan

First Post:
Originally I had classes for each arithmetic sum because they contained multiple functions. However, I realised that I did not need one function to get the number, and another to work out the answer and show it on the screen, thus I combined them into one function.

I never got around to getting rid of the classes, but I shall do this next. I am also new to classes, so it did help me to get more comfortable with them :P From the videos I am watching at the moment (just to get a broad sense of C++ before I read into further detail), I have actually just learnt about making data members private as well as constructors so this is also something I will weave into the next version of my calculator program.

Thanks for the heads up on the tutorials, I shall give them a good read as soon as I have enough time :D

Second Post:
Good quotation!!!

Ok, great suggestion! I shall implement this in v2 of my build.

@mandy012

Ah, so you think I should put switch statements instead of if statements? If so, for next time I will learn about switch statements and put this into v2 of my calculator program

@MiiNiPaa

Thanks for helping Mandy out (and therefore me as well) I will make sure to put case 1: instead of case '2':

@Zereo

Ah, great! You took Mandy012's and MiiNiPaa's comments and managed to summarise them - this is a great help! As said above I will put switch statements in the next version of my program, as well as getting rid of all the classes ;)

@MatthewRock

Hey!!!!

Oh ok aha... You are a good teacher, so thank you for making me think differently and outside the box.

What I meant with my comment is that it takes the user input (menu choice) and returns it to main, so that my main function can use this value to determine which if statement to activate. If that makes sense?

Yeah, sorry about doing this - I never realised it would cause so much fuss! This is something I am going to change for v2 of the program, and was there because previously I had multiple functions for each class which I later realised could be condensed to just one function (as stated above). Me too :) I will weave Zereo's switch statment idea into my code, as well as getting rid of the classes in order to make it much more simple :P

Ah, now his comment makes much more sense! So instead of having int x etc. I should have string x? This way, if a letter is inputted instead of a number, my program will hopefully not crash? I shall look into different variable types after replying to all these answers!

Yes, I am at the beginning of my education, which is why I have no doubt that my program is riddled with poor practice and bad code leading to poor security (as well as crashes). This is something I hope to fix as I improve. Could you possible give me a really small piece of sample code showing how to do character strings? Or is it easy to read up on them somewhere?

Will do all of these! Thanks a lot man, you have been a REALLY huge help :)

@giblit

I do not think most of your posts are aimed at me so I will keep out of what you are talking about. Just wanted to apologise for saying that what you did earlier was wrong :) I will look through the new code that you posted - and try and understand it!


To ALL:

Once again, a HUGE thankyou for all of your help, and sorry for my slow replies to this thread (I have a busy day!)

From your suggestions, for my next version of the calculator I am going to:

1. Insert Switch Statements

2. Take away the classes

3. User input security (putting a char instead of int etc.

4. Check for divide by zero in division

And it is also great to see discussion amongst yourselves. I shall keep this thread open so that when I have done v2 of the calculator I can post my code here, and go from there!
Last edited on
v2 of the program!!! Change log:
1. Taken away classes
2. User Security for main menu
3. Able to return to menu

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
#include <iostream>

using namespace std;


//Menu Function
string CalculatioOptions(string answer){
     //DISPLAY MENU
     cout << endl;
     cout << "What would you like to do: \n";
     cout << "1. Addition \n";
     cout << "2. Subtraction \n";
     cout << "3. Division \n";
     cout << "4. Multiplication \n";
     cout << "5. Quit\n";
//TAKE USER INPUT AND RETURN IT
     cin >> answer;
     cout << endl;
     return answer;

}



//Addition Function
          string AddNumber(string yes){
             int x;
             int y;

         cout << "Please enter two numbers: \n";
         cout << "First Number: ";
         cin >> x;
         cout << endl;
         cout << "Second Number: ";
         cin >> y;
         cout << endl;
//ADDITION CALCULATION
         int answer = x + y;
         cout << "The answer is: ";
         cout << answer << endl;
//REPEAT OR GO TO MENU
           cout << endl;
  cout << "Press anything to do another addition calculation, or press q to return to menu\n";

     cout << "Answer: ";
    cin >> yes;
    cout << endl;
     return yes;
          }


//MINUS FUNCTION
        string MinusNumber(string yes){
         int x;
         int y;


         cout << "Please enter two numbers: \n";
         cout << "First Number: ";
         cin >> x;
         cout << endl;
         cout << "Second Number: ";
         cin >> y;
         cout << endl;
//SUBTRACTION CALCULATION
           int answer = x - y;
           cout << "The answer is: ";
           cout << answer;
           cout << endl;
//REPEAT OR RETURN TO MENU
  cout << "Press anything to do another minus calculation, or press q to return to menu\n";

  cout << "Answer: ";
  cin >> yes;
    cout << endl;
  return yes;

}
//DIVISION FUNCTION
         string DivideNumber(string yes){
         int x;
         int y;

         cout << "Please enter two numbers: \n";
         cout << "First Number: ";
         cin >> x;
         cout << endl;
         cout << "Second Number: ";
         cin >> y;
         cout << endl;
//DIVISION CALCULATION
         int answer = x / y;
         cout << "The answer is: ";
          cout << answer;
          cout << endl;
//REMAINDER CALCULATION
          int remainder = x % y;
          cout << "And the remainder is: ";
          cout << remainder;
          cout << endl;
//DO ANOTHER CALCULATION OR RETURN TO MENU
          cout << "Press anything to do another division calculation, or press q to return to menu\n";

  cout << "Answer: ";
  cin >> yes;
    cout << endl;
  return yes;
}
//MULTIPLICATION CALCULATION
         string MultiplyNumber(string yes){
         int x;
         int y;

         cout << "Please enter two numbers: \n";
         cout << "First Number: ";
         cin >> x;
         cout << endl;
         cout << "Second Number: ";
         cin >> y;
         cout << endl;
//MULTIPLICATION CALCULATION
         int answer = x * y;
         cout << "The answer is: ";



         cout << answer;
         cout << endl;
//DO ANOTHER CALCULATION OR RETURN TO MAIN MENU
         cout << "Press anything to do another multiplication calculation, or press q to return to menu\n";
         cout << "Answer: ";

  cout << "Answer: ";
  cin >> yes;
    cout << endl;
  return yes;

}

int main(){

//Defining Variables
string useroption;
string doAgain;


do{
//BEGINNING OF PROGRAM
useroption = CalculatioOptions(useroption);

if(useroption == "1"){

        do{
        doAgain = AddNumber(doAgain);

        }while(doAgain != "q");
}


if(useroption == "2" ){

 do{
        doAgain = MinusNumber(doAgain);

        }while(doAgain != "q");

}

if(useroption == "3" ){

 do{
        doAgain = DivideNumber(doAgain);

        }while(doAgain != "q");


}

if(useroption == "4" ){

 do{
        doAgain = MultiplyNumber(doAgain);

        }while(doAgain != "q");
}

}while(useroption != "5" );
}


Tried to insert switch statements but not sure how to do that with strings? Some help in that department would be great!
U can only do switch with char or int if it is a string u would do like string[0] to get first char or what ever char u want good job though with calc and I would suggest ignore after cin for security in program incase someone tries like 1 44 86 but its up to you
Last edited on
closed account (3qX21hU5)
Or just use integers since that is what they are made for ;p

You don't need to use strings or chars to handle user input errors that break the stream. Here is how you are suppose to handle user input errors that break streams. Never use strings or chars just to handle that kind of errors because you will just be causing more errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <limits>

using namespace std;

int main()
{
    int userInput;

    while (true)
    {
        cout << "Enter a string or char to test error handling" << endl;
        cin >> userInput;
    
        
        // This handles the error handling if the user enters anything but a integer.
        if (cin.fail())
        {
            cout << "Bad input! Try again!" << endl;
            cin.clear();
            cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
        }
    }
}





Last edited on
that works except if someone does both an int and a char (1a) it will think you entered 1 then a so it would output
Enter a string or char to test error handling
1a
Enter a string or char to test error handling
Bad input! Try again!
Enter a string or char to test error handling

instead of just
Enter a string or char to test error handling
1a
Bad input! Try again!
Enter a string or char to test error handling
Last edited on
Topic archived. No new replies allowed.