简体   繁体   中英

Returning value from function into a value being tested by a while loop. C++

I am creating a basic calculator program using constructors by making classes in other ".cpp" files and calling them in header files. The program worked perfectly fine the way I wrote it. I decided to then add a question at the end asking if the user would want to continue by pressing "c" or "C". I created a function to test for this. I am able to return two different values based on if c was pressed or if it was not. How do I assign that value to "x" which is being tested in the while loop? I want this to either end the program or continue it.

I did not include the header files or ".cpp" files necessary for the constructors, but I don't think they are necessary to find how to set x to the returned value of the function.

#include <iostream>
#include "Add.h"
#include "Sub.h"
#include "Mult.h"
#include "Div.h"

using namespace std;

int cont(char input);

int main()
{
    char operatr;
    int x = -2;
    char y;

    while (x = 1) {

        cout << "Enter operator (+, -, *, or /): ";
        cin >> operatr;


        if(operatr =='+'){
            Add ob;
            cout << "Would you like to continue? (Press \"c\" to continue and any key to escape.)";
            cin >> y;
            cout << (cont(y));
            x = (cont(y));
        }
        if(operatr== '-'){
            Sub ob;
            cout << "Would you like to continue? (Press \"c\" to continue and any key to     escape.)";
            cin >> y;
            cout << (cont(y));
            x = (cont(y));
        }
        if(operatr=='*'){
            Mult ob;
            cout << "Would you like to continue? (Press \"c\" to continue and any key to escape.)";
            cin >> y;
            cout << (cont(y));
            x = (cont(y));
        }
        if(operatr=='/'){
            Div ob;
            cout << "Would you like to continue? (Press \"c\" to continue and any key to escape.)";
            cin >> y;
            cout << (cont(y));
            x = (cont(y));
        }
    }
    return (0);
}

int cont(char input) {
    int a;
    switch(input) {
        case 'c':
            a = -2;
            break;

        case 'C':
            a = -2;
            break;

        default:
            a = 0;
            break;
     }
return(a);
}

Couple of issues:

  1. You're testing x being equal 1 in the loop but using -2 in your conf(int) method.
  2. Your while loop is actually not testing x bit "assigning" 1 to x.

You meant to do:

while (x == -2)

You could also.just save on method calls to #cont with:

x = cont(y);
cout << x;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM