General Advice For Newbie!

Just started learning C++, I have experience in Python and Java. I created this small calculator program to help learn the basics and get an understanding of what I'm dealing with.

I've incorporated some "good practices" that I've seen online. Are these genuinely good practice? I've also used a lot that I don't understand so any comments on this code is welcome.

Good Practices Used:
- Instead of using namespace std; I specify the specific parts used to minimize how much the program needs to import.
- Declared functions separate from function definition
- Using <printf> instead of <cout>

Things I don't fully understand:
- I've used <const char *> and from what I understand char* refers to the pointer allowing char[0] whereas char would not do this.
- Im getting an error from the <const char * getUserOperation()> function's return value of operation. The error is "The address of the local variable may escape the 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
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
#include <iostream>

using std::cout;
using std::endl;
using std::string;
using std::cin;
using std::getline;
using std::stod;
using std::invalid_argument;
using std::stringstream;

double subtract(double num_1, double num_2);
double add(double num_1, double num_2);
double multiply(double num_1, double num_2);
double divide(double num_1, double num_2);
double getUserDoubleInput();
const char * getUserOperation();
double calculate(double num_1, double num_2, const char * operation);



int main() {
    double num_1;
    double num_2;
    const char * operation;



    num_1 = getUserDoubleInput();
    num_2 = getUserDoubleInput();
    operation = getUserOperation();


    printf("%.2f\n", calculate(num_1, num_2, operation));


    return 0;
}

double subtract(double num_1, double num_2){return num_1 - num_2;}
double add(double num_1, double num_2){return num_1 + num_2;}
double multiply(double num_1, double num_2){return num_1 * num_2;}
double divide(double num_1, double num_2){return num_1 / num_2;}

double getUserDoubleInput(){
    string input;
    double num;
    while(true) {
        try {
            printf("%s",
                    "Please Enter A Number: ");
            cin.clear();
            getline(cin, input);
            num = stod(input);

            break;
        } catch (invalid_argument const &e) {
            printf("%s",
                   "Invalid Entry\n");
        }
    }
    return num;
}

const char * getUserOperation(){
    string input;
    const char * operation;
    while(true) {
        try {
            printf("%s",
                   "What Operation Would You Like To Do? multiplication(*), addition(+), subtraction(-), division(/): ");
            cin.clear();
            getline(cin, input);
            operation = input.c_str();
            break;
        } catch (invalid_argument const &e) {
            printf("%s",
                   "Invalid Entry\n");
        }
    }


    return operation;
}

double calculate(double num_1, double num_2, const char * operation){
    double result = 0.0;
    if(operation[0] == '-'){
        result = subtract(num_1, num_2);
    }else if(operation[0] == '+'){
        result = add(num_1, num_2);
    }else if(operation[0] == '*'){
        result = multiply(num_1, num_2);
    }else if(operation[0] == '/'){
        result = divide(num_1, num_2);
    }

    return result;
}
Last edited on
Using <printf> instead of <cout>

Wrong. printf is C, not C++. If you're looking for C++ good practices, stick with C++ facilities.

operation = input.c_str();
input is a local variable that disappears off the stack when you exit getUserOperation(). Therefore your return value is invalid.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.


General Advice For Newbie

Totally ignore your 3rd "Good Practices" idea, using printf instead of std::cout. It is a really BAD idea using C functions when learning C++.

The first two "Good Practices" are indeed good ideas.

You might want to poke your nose at a very good and free online tutorial, Learn C++:
https://www.learncpp.com/

Biggest piece of advice for someone starting out, C++ is NOT Java. C++ is NOT Python. C++ is NOT C.

There are definite common syntax features, but to properly learn C++ you need to ignore what the other languages do for a particular task.

C++ was originally derived from C, way back when, but after years and decades of evolution the two now are almost entirely different programming languages.
skip over C style strings and the special cases of char* type for now. You can circle back to it later when you understand more, but to put it in a nutshell:
for a long time C and c++ shared "string" tools which were really just the C tools. Those are still available in c++, but you should avoid them in favor of c++ std::string which is much like the java one. C++ has actually 3 string types that play together, string, stringstream, and stringview. Its an unfortunate history that got us to that point, but all 3 are useful for various things.

C style basic arrays are handy at times, but vector or std::array are the OOP versions that may make you feel more at home. C arrays are not objects, they are raw lumps of memory with a pointer / access point provided via the variable's name.


Shouldn't getUserOperation() return just a type char - instead of pointer to char - and shouldn't that function check that the operation is valid?

Variables should be initialised when defined. l23 defines and then L29 sets it value. L29 could define and initialise.
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
#include <iostream>

/*
 Input 2 decimal numbers, specify arithmetic operation, display result.
 */

double getDouble();
char getOperation();
double getResult(const double, const double, const char);

int main()
{
    double num_1{0};
    double num_2{0};
    char operation;
    
    num_1 = getDouble();
    num_2 = getDouble();
    operation = getOperation();
    
    std::cout
    << num_1 << ' ' << operation << ' ' << num_2 << " = "
    << getResult(num_1, num_2, operation) << '\n';
    
    return 0;
}

double getDouble()
{
    double n;
    std::cout << "Please enter a decimal number: ";
    std::cin >> n;
    return n;
}

char getOperation()
{
    char op;
    std::cout << "Enter operation +,-,* or /: ";
    std::cin >> op;
    
    std::string options{"+-*/"};
    if( options.find(op) == std::string::npos )
        std::cout << "Invalid operation selected\n";
    
    return op;
}

double getResult(const double a, const double b, const char op)
{
    if(op == '-')
        return a - b;
    else if(op == '+')
        return a + b;
    else if(op == '*')
        return a * b;
    else
        return a/b;
}


Please enter a decimal number: 3.1
Please enter a decimal number: 2.1
Enter operation +,-,* or /: +
3.1 + 2.1 = 5.2
Program ended with exit code: 0


Please enter a decimal number: 2.1
Please enter a decimal number: 0
Enter operation +,-,* or /: /
2.1 / 0 = inf
Program ended with exit code: 0


Topic archived. No new replies allowed.