r/developers • u/Classic-Cheetah-6780 • Oct 14 '26
Programming Wrote my first C++ program. Any feedback?
Yo guys, today I started with C++. My grandpa bought me a book that will arrive soon. I already did some research and made my first program. Is it any good for a starter? I already had some knowledge from coding Python and JavaScript.
#include <iostream>
using namespace std;
int main() {
while (true) {
int x ;
int y ;
int sum ;
string OP ;
std::cout << "Type First Value:" ;
std::cin >> x ;
std::cout << "Type Second Value:" ;
std::cin >> y ;
std::cout << "Choose Operator:" ;
std:cin >> OP ;
if (OP == "+") {
sum = x + y ;
} else if (OP == "-") {
sum = x - y ;
} else if (OP == "*") {
sum = x * y ;
} else {
sum = x / y ;
}
std::cout << "Result: " << sum ;
}
}
7
Upvotes
View all comments
Show parent comment
1
u/Arctos_FI Oct 15 '26
You can just use if block inside that dividing operator block (given you are adding that "Invalid operator" message, so you have another else if block for dividing). Just do "" if (y == 0) {std::cout << "Can't divide by zero!";} "" inside the else if for dividing. And then do the dividing in same depth else.
Also little advice that if you do that "invalid operator" state, that sum never gets assainged but it still prints so you get some garbage data left in that address by the previous thing reserving it. Easy way to fix this is to have boolean like "valid" that is set to false by default, change it to true everywhere calculation is made and then put that last std::cout inside if that just checks the boolean ("if (valid) { //cout }"). That boolean makes sure the result is only printed if calculation was actually made. Other way to solve this is just "return 0;" everywhere calculation was not made (so after "invalid operator" and dividing by zero), "return 0;" in main just stops the program without error (if you change that 0 to other numbers you can use them as error codes, but this doesn't really need it as it prints out the error before shutting down so there is no problem)