Search

1.12 — Chapter 1 comprehensive quiz

Question 1

Write a single-file program (named main.cpp) that reads two separate integers from the user, adds them together, and then outputs the answer. The program should use three functions:

  • A function named “readNumber” should be used to get (and return) a single integer from the user.
  • A function named “writeAnswer” should be used to output the answer. This function should take a single parameter and have no return value.
  • A main() function should be used to glue the above functions together.

Hint: You do not need to write a separate function to do the adding (just use operator+ directly).
Hint: You will need to call readNumber() twice.
Hint: If you’re using visual studio with precompiled headers, don’t forget to #include “stdafx.h”.

Show Solution

Question 2

Modify the program you wrote in exercise #1 so that readNumber() and writeAnswer() live in a separate file called “io.cpp”. Use a forward declaration to access them from main().

Hint: If you’re having problems, make sure io.cpp is properly added to your project so it gets compiled (see lession 1.8 -- programs with multiple files for more information on how to do this).

Show Solution

Question 3

Modify the program you wrote in #2 so that it uses a header file (named io.h) to access the functions instead of using forward declarations directly in your code (.cpp) files. Make sure your header file uses header guards.

Show Solution

2.1 -- Fundamental variable definition, initialization, and assignment
Index
1.11a -- Debugging your program (watching variables and the call stack)

451 comments to 1.12 — Chapter 1 comprehensive quiz

  • Hervé

    Seeing as how people are all posting their calculators, I'll post mine aswell for some feedback

    main.cpp

    division.cpp

    subtraction.cpp

    multiplication.cpp

    addition.cpp

    choices.cpp

    I do realise I could have split more of the code from 'main.cpp' into the other files, but now that it's up and working, I dont really want to spend the time to do it. Any advice or criticism is welcome as, shown by my comment regarding the '&' sign and possibly plenty of other terminology errors, I am new to C++ any advice is helpful.

    EDIT: I just realised this was far longer than I had expected, feel free to skip a lot of the top part in 'main.cpp' as it mainly is the same thing repeated four times with minor differences each time.

    • nascardriver

      Hi Hervé!

      main.cpp/General:
      * Sort your includes.
      * Prefer the <c*> headers over <*.h> (<cmath> over <math.h>, <climits> over <limits.h> and so on).
      * I don't think you're using ncurses.
      * Use the namespaced versions of standard functions (std::sqrt)
      *

      * Initialize your variables with uniform initialization.
      * Line 39-41 are equivalent to Line 46-48. Don't repeat yourself.
      * Initialize chars to 0, not '0'
      * Line 71: Avoid magic numbers. Use std::numeric_limits<double>::digits10.
      * Line 77, 81, 85 and 89 are repetitions. Don't repeat yourself. If you don't have a break in a case the code below will be executed. So you can remove the contents of all cases except case '/'.
      * You already said it, @add, @sub, @div and @mult are almost identical. Don't repeat yourself.
      * Line 412: choices != choice. If you didn't notice this you should use different names.

      Every math file:
      You don't need any of those includes. All they do is increase compilation time. You're not even using the functions in there. Remove those files.

      choices.cpp:
      @choices only gets called after you've already switched the operation, but you're switching it again here.

      • Hervé

        Thanks for the feedback! I have since followed your advice and significantly cut the length of the program by deleting all four math files and combining the math functions into one. I feel kinda embarrassed to ask since you have clearly done quite a lot to help me, but I don't quite understand what you mean by 'choices != choice. If you didn't notice this you should use different names'. I realise you were pointing at the 'while(&choices)' form the do-while loop, but did you mean that the code was replacing the '&choices' by 'choice'? Sorry if my question is stupid, but I don't really have much experience with do-while loops and don't understand what you meant.

        P.S. Just being curious here but what benefits does using the namespace version of functions over the standard function give? Or is it just for good habits?

        • nascardriver

          Always ask if you don't understand something or you'll get into bad habits.

          You have a variable named "choice" and a function named "choices". I though you were trying to do some checks with the variable and accidentally added an 's' to the end.
          To be honest, I don't understand what you were trying to achieve here. I don't see a way to stop that loop so you might as well use

          > what benefits does using the namespace version of functions over the standard function give?
          No benefits. The non-namespaced versions are leftovers from earlier versions of C++ or C. Most implementations of the <c*> headers declare the functions in the global namespace, but using the namespaced variants is the proper way to access them.

          • Hervé

            Thanks again. I did mean to have 'choice' as a variable and 'choices' as a function. I was just using the do-while loop for an infinite loop although I didn't really know how to do so, I guess you just told me the answer. I also added in 'std::numeric_limits<double>::digits10' instead of 'std::cout.precision(10)' but it didn't increase the maximum accuracy of a number and ended up showing numbers with higher than 7 digits in scientific notation, did I use it wrong or something, I realise this is something I will probably learn later on, but how exactly would it avoid showing imaginary numbers and how am I supposed to implement it into the code?

            I did it like this, which is probably why I didn't get it to work?

            Many thanks again for all the help!

            • nascardriver

              is just a number, you still need to call @std::cout.precision or use @std::setprecistion.

              The advantage of using this value rather than 10 is
              a) Everyone knows what this value will do (Or look it up)
              b) This value can vary on different systems. If you use 10 and some system has a higher precision than 10 you'll be missing some digits.

  • Beesta

    So, I'm having a fun lil issue. I'm using MVS and it refuses to compile even if I use the code thats in the answers (given that I added the #include "stdafx.h")
    It's saying that cin and cout arent members of std. error code is c2039 and c2065.

    • Alex

      Assuming you haven't made an error somewhere (e.g. including iostream.h instead of just iostream), it's possible your compiler is just significantly out of date.

      • Beesta

        I'll go ahead and post my code, but its basically the same as the solutions. Also, my version of Visual Studio should be one of the newest, version 15.6.4.

        io.cpp

        main.cpp

        io.h

  • Cumhur

    Really cool to write some codes and see they work!
    Thanks for your effort, i want to ask  at end the lessons  if i can be able to code complex 2D platform games. Thanks again!

  • Qbert

    Hello,

    My programs accomplish the goals of the quiz when the user inputs "expected" values. I wanted to see what happens when I try other inputs.

    Can you explain what C++ is executing when I input a decimal for the first value? What appears to happen is it does not ask for a second value, puts in an unexpected number, omits the addition, and then ends the program.

    When I put a decimal value for the second value though, it ignores everything after the decimal but runs as expected otherwise.

    I include my code below in case it is just something with the way I have written it.

    • nascardriver

      Hi Qbert!

      Anything you write into your console will be stored in a buffer. std::cin looks at that buffer and tries to extract an int from it. It doesn't care if there is anything after the int. The int will be removed from the input buffer.
      Let's look at what happens in a smaller sample program:

      Same happens with for example 123hello as input.

      References
      Lesson 5.10 - std::cin, extraction, and dealing with invalid text input

  • Dear Teacher, please let me say you what I do not understand. I have written four files: main.cpp, io.cpp, io.h, and qio.h. In IDE online
    https://www.onlinegdb.com/online_c++_compiler#
    program works fine. But two header files are identical save their names.
    io.cpp

    io.h

    qio.h

    main.cpp

    Regards.

  • Zane

    Las calculadoras? Si!

    Calculator Main.cpp

    Math.cpp

    • nascardriver

      Hi Zane!

      Good job solving the quiz!

      main.cpp

      Math.cpp

  • seb

    If we're posting calculators, I guess I'll post mine.

    calc_head.hpp

    main.cpp

    get_number.cpp

    get_operator.cpp

    print_op.cpp

    calc.cpp

    • nascardriver

      Hi seb!

      Since you used content that hasn't been covered yet I'll do the same.

      main.cpp
      Line 6: Uniform initialization is preferred. (Same goes for all other initializations) (Lesson 2.1)
      Line 8: @std::cin.clear clears the error flag that gets set when an error occurs. There's no point in calling it here.
      Line 9: You're extracting input via @std::cin::operator>>. You don't need @std::cin.ignore here.
      Line 12,16: You don't need an empty string to output a new line

      Line 19: Unnecessary
      Splitting user input, calculation and printing into separate functions would've been nice.

      get_number.cpp
      Line 5: Initialize your variables. (This goes for all other variables too)

      get_operator.cpp
      Never use goto.
      Line 16: You don't need std::getline, std::cin >> or std::cin.get are enough.
      Line 19: std::strings are converted to const char * by using std::string::c_str(). What you did might not work with all implementations of std::string.
      Line 20, 23, 26, 29: strcmp isn't used for std::strings. std::string has an == operator

      The do-while-loop isn't doing anything, because you messed everything up by using goto. If you removed the goto it should work without further changes.

      calc.cpp
      Unnecessary use of temporary. You could've returned the results of the calculations directly.

      All in all, there are sevaral issues, but that's nothing to worry about. We're at the start of the lessons and you'll learn how to do it probably.

      • seb

        main.cpp

        Line 6: I was only aware of copy initialization when I made this. I only know what I've learned from this website, and google(which turns up old questions on stackoverflow) when I want to do something that hasn't been covered yet(I just finished chapter 2.1).

        Line 8: ok.

        Line 9: I do need this, or the next function thinks I'm still pressing return and tries to skip a part of my program.

        Line 12, 16: I know what happened here. I tried using std::endl by itself at some point, and I also probably tried using std::cout << << std::endl (unaware of the proper usage of << at the time). I found something that worked and kept using it.

        line 19: I like to test my compiled applications outside of the ide.

        "Splitting user input, calculation and printing into separate functions would've been nice." Easy now, this is just a test program to help me get my bearings (which hours to make). I have zero previous experience with c++, almost zero with programming in general, and am doing this as a hobby (using whatever resources I can find online). I'm just happy it works.

        get_number.cpp

        line 5: int a; is initialized via std::cin > a; on the next line. I don't see the problem.

        get_operator.cpp

        what's wrong with goto?
        (scratch that, I looked it up)
        if goto is depreciated, shouldn't it be removed from the c++ standard library?

        line 16: I print a "'user input' is an invalid operator" statement using the input from getline;
        I used cin.get at first, but if any spaces are entered into the console, I get multiple such statements, since each character or set of characters after a space is treated as a new entry.

        line 19: "What you did might not work with all implementations of std::string."
        I'm not exactly sure what you mean by "all implementations of std::string", but I think I catch your drift.

        Line 20-29: Oh, so I can use the string directly. (I had it converted for something else that I removed. I think I was trying to return the string to main as a char array. I just learned about pointers and references while trying to do something else today; but they seem kind of unreliable, I must be using them wrong).

        "The do-while-loop isn't doing anything"
        I had to search online to figure out how to use a loop at all. I'd been learning c++ for maybe 3 days (so like 5 or 6 now?).

        You're right, the loop works fine without goto, but I get the warning "label LOOP defined but not used", for some reason (which may be why I thought I needed goto in the first place).

        "calc.cpp
        Unnecessary use of temporary."
        stylistic preference. (you're referring to int d; right?)

        • nascardriver

          > int a; is initialized via std::cin > a;
          That's not an initialization, that's an assignment. You shouldn't rely on functions to be able to handle uninitialized variables.

          > if goto is depreciated, shouldn't it be removed from the c++ standard library
          The problem with removing deprecated features is that there is still source code out there that's using these features and you wouldn't be able to compile them if it was just removed. It'd be nice if these features were marked as deprecated by IDEs, but unfortunately that's not a thing.

          > but I get the warning "label LOOP defined but not used"
          Labels are only used in combination with goto, they don't serve a purpose on their own.

          > you're referring to int d; right?
          Yep. I do it like you do when I'm debugging and I want to see the value before it's returned. Your compiler will remove the temporary to increase performance so there's no difference in the end, but I like imagining that my compiler doesn't optimize stuff.

          For 3 days of learning you've done a good job, keep it up!

          • seb

            "That's not an initialization, that's an assignment. You shouldn't rely on functions to be able to handle uninitialized variables."

            Assigned, my bad; I'm still new to the terminology.
            (I know the difference but didn't think to express that awareness).

            So if I want an empty variable, I  should just initialize it with a zero?
            int a{0};

            "Labels are only used in combination with goto, they don't serve a purpose on their own."

            Oh, ok. so just do{}while; and not label.do{}while;

            "Your compiler will remove the temporary to increase performance so there's no difference in the end, but I like imagining that my compiler doesn't optimize stuff."

            Are some compilers better than others at optimization, or just in general?
            I'm using mingw-w64 (w/ code::blocks).

            • nascardriver

              > So if I want an empty variable, I  should just initialize it with a zero?
              If it's a number, yes. For other data types you use their default value (0, 0.0, 0.0f, "", nullptr, etc.)

              > Oh, ok. so just do{}while; and not label.do{}while;
              Yes, do-while-loops are covered in lesson 5.6

              > Are some compilers better than others at optimization
              Probably, but I don't know which ones are better than others.

  • mitch

    what does this have to do with bernie sanders?

  • Yus K

    CalculatorHeader.h

    Calculator.cpp

    CalculatorMaths.cpp

    CalculatorInputs+Outputs.cpp

    I tried the calculator example using a bit of my own addings also to practice my skills.

    Looking back at this code my ideas of what can be added are
    1) Header guards (didn't understand this correctly so i have to re read the chapter)
    2) Use comments to leave notes explaining useful info

    If anyone has any advise on my code, or anything to add please post as im new and eager to learn from people who have more knowledge than myself

    • nascardriver

      Hi Yus!

      CalculatorHeader.h:
      Bad file name, the file extension says it's it header, having 'Header' in the name is redundant.

      CalculatorInputs+Outputs.cpp:
      Bad file name, stick to letters, underscores (and numbers).
      Also, since this is the source file defining the functions declared in @CalculatorHeader it should have the same name.
      Line 6, 13: Initialize your variables.

      @calculation:
      @y: Bad variable name, operation or similar is better.

      You'll learn about further improvements to your code in upcoming lessons. So far you've done a good job.

  • Jimi

    The calculator i made is a little unnecessarily complicated as while making it i wanted to try out things like the if and goto commands, as well as make sure i’ve got a handle on all the things discussed in older lessons.

    main.cpp

    askStuff.cpp

    mathFunctions.cpp

    askStuff.h

    • Jimi

      Oh, and all the std::cout << std::endl; statements are there just to add newlines into the program. Really they're pretty unnecessary as they make the code more difficult to read while making the program a little prettier. I'm sure there's a better way to add newlines but this is the only method i know.

    • nascardriver

      Hi Jimi!

      > I’m sure there’s a better way to add newlines but this is the only method i know.
      There's '\n'.
      std::cout << "Hello\nWorld" << std::endl;

      Output

      General stuff
      Don't ever use goto! All modern languages offer various other, cleaner, reader friendlier ways of achieving the same results.
      Try to limit each line to a maximum of 80 characters. Longer lines might not display correctly on small screens.

      main.cpp
      Line 12: Bad variable name

      askStuff.cpp
      Line 4: Unnecessary forward declaration, this will add extra work if you decide to change the function signature
      Line 8: Initialize your variables, this goes for all other variable declarations, I won't list all of them
      @askInput and @recordInput could be merged into one function to prevent the creation of 1 variable and 1 function call

      mathFunctions.cpp
      Line 4: Bad function name or behavior. @doMath should do math and not print anything or have a different name.
      Line 6+: Use 'else if'

      PS: Edit your posts instead of deleting and re-posting. Syntax highlighting will work after refreshing the page.

      • Jimi

        Thank you for the feedback!
        I agree that some variables and functions have dumb names, I initially mixed up some variables and had issues because of that.

        A few notes though.

        In doMath last.cpp, how would I use else if? Maybe I don't fully understand the statement, but I don't think I need to do anything if, for example, x was not 1.

        The reason recordInput is it's own function is because it's being used by main, askInput and askOperand. I can reuse the function that way.

        • nascardriver

          > In doMath last.cpp, how would I use else if?

Leave a Comment

Put all code inside code tags: [code]your code here[/code]