Anthony Salazar
Anthony Salazar

Reputation: 21

can you use cin twice?

I'm trying to do a calculator type thing to practice with functions (I'm a beginner) and for the user to use, addition, subtraction, mult. or division the user has to choose a mode which is the job of the variable mode so I used cin so the user can enter a number. but once the user chooses the mode then the user would need to input the values but to do that i would need to use cin again, but the screen where the user inputs the value doesn't appear. what should I do? (this is not complete)

#include <iostream>
using namespace std;

double mode4 (double x, double y){
    double sum;
    sum = x + y;
    cout << "sum is: " << sum <<endl;
    return 0;
}

int main() {
   int *mode = new int;

cin >> *mode;
if (*mode > 4 || *mode == 0){
  *mode = 4; 
}

if (*mode == 4){
   double num1;
   double num2; 
   cin >> num1 >> num2;
    mode4(num1, num2);
    delete mode;
}

cout << *mode << endl;
    return 0;
}

Upvotes: 2

Views: 457

Answers (2)

Deepak Patankar
Deepak Patankar

Reputation: 3282

You will have to input the value of num1 and num2 in the same screen, cin doesn't generate a new screen for every time it is called. This is how your calculator screen looks like :

0
2 3
sum is: 5
4

If you want to take the next input in a new screen then you can use this answer

Upvotes: 3

john
john

Reputation: 87959

Not the answer to your question but I just have to mention

int *mode = new int;

cin >> *mode;
if (*mode > 4 || *mode == 0){
    *mode = 4; 
}

Don't gratuitously use pointers, this is simpler, safer, more efficient, less typing etc.

int mode;

cin >> mode;
if (mode > 4 || mode == 0){
    mode = 4; 
}

etc.

If you need an integer variable just declare one. There's no need to use an integer pointer and allocate the integer.

Upvotes: 1

Related Questions