r/cpp_questions • • Jul 23 '20
OPEN FOR BEGINNERS: Finally, I just finished my calculator! Beginners are welcome to check the code and learn some stuff
Hi everyone! I just finished my calculator in C++. It's not anything crazy it's just a calculator but I just wanted to share for people starting C++ cause even tho it's not a hard program to make, the code is very commented (for people to understand, actually almost everything is explained) and a lot of good practices are used like:
1 proper error handling
2 use of functions so we won't re write the same code
3 the program keeps running forever until you give 'S' as the operator option
When you run it you will give a number, then an operator, and then a number again. After that you can print the result giving '=' as an operator, quit given 'S' or keep getting new values. This keeps on forever till you decide to quit. So yeah, here is the code for anyone that wants to check it out. Also other than beginners anyone can see the code just of curiosity and maybe tell me if you believe I could have made something better (I don't have a lot of experience myself).
EDIT: I'm glad you guys enjoyed it and I'm thanks for anyone that gave feedback. The code is now updated using some of the "tips" people have gave in the comments. Still not adding anything fancy and keeping it beginner friendly but some things have changed and now looks better (switch statement being the biggest example). Have a great day everyone!
3
u/b00tstr4pper Jul 23 '20
The way you’ve done this is actually very interesting. Thanks for sharing!
3
u/be-sc Jul 23 '20
Interesting approach. :) Probably not the worst example of a beginner friendly calculator implementation. I like that you focus on simple input/output and basic looping and don’t add anything fancier.
A few notes:
get_num()andget_op()ask the user for input. Their names should reflect that. get is too unspecific. First idea:ask_user_for_number()andask_user_for_operator(). Also, theextraparameter ofget_op()is unclear without reading the comment in the function.get_num(): No need for thenumvariable. In the try block you canreturn stof(pre_num);directly. Makes the function significantly simpler and avoids the uninitialized variable declaration.constcorrect.-14
u/alexeyneu Jul 23 '20
didn't see code and dont wanna to. But i'm more than sure that
in your case does not assume use of
fetestexcept()or_statusfp(). So try to use one0
u/[deleted] Jul 23 '20
[deleted] — view deleted comment
0
u/[deleted] Jul 23 '20
[deleted] — view deleted comment
0
u/[deleted] Jul 23 '20
[deleted] — view deleted comment
11
u/[deleted] Jul 23 '20
[removed] — view removed comment