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)

328 comments to 1.12 — Chapter 1 comprehensive quiz

  • me

    you haven’t mentioned what void is yet

    [ It was covered in a first look at functions. “A return type of void means the function does not return a value”. -Alex ]

  • There’s a much easier code for Question 1:

    [ Code removed so as not to give hints as to how to solve the problem ]

    • Juiceh, the point of the exercise isn’t to write the easiest or most efficient code. The exercises are worded to encourage people to use various concepts that have been covered in the preceding sections.

      • Trophy

        I’m sorry to reply to your comment even though this has nothing to do with it, but I can’t figure out how to comment without replying. Anyway, there’s a problem with your code. Basically you’re telling the compiler to go to main.cpp to io.h and then to io.cpp, but that isn’t how the compiler reads it, the compiler reads it as main.cpp to io.h to main.cpp which causes the compiler to stop before “ReadNumber()” and “WriteAnswer()” are defined, even though they’ve been declared. I kept getting “undefined reference” error, because of the way the program was set up, so I put ‘#include “io.cpp”‘ in the header file and it worked again, which revealed the problem. Am I wrong, or is my compiler just not set up correctly?

        • Alex

          My code is fine. Make sure you’ve added io.cpp to your project so it gets compiled in.

          It’s bad form to #include a .cpp file.

        • Daniel Ricci

          The linker should detect both your cpp files (main and io) and will sandwich them both together along with some other dependency libraries.

          If you wanted to write a header file then there would be no need for a forward declaration in your Main.cpp, you would just #include "io.h" and the .cpp file would be sandwiched during compilation.  Both ways work, but normally having a seperate .h file will allow us to avoid forward declarations in our Main, since including the header would just do that for us automagically.

      • shakey2

        My code ended up almost identical to your solutions >.< the only difference is I didn’t use "using namespace std"(because people keep going on about name collisions), and I put "the sum of those numbers is: " inside main() instead of writeAnswer(). I felt it’d be better if I wanted to call writeAnswer() for a different purpose and didn’t want that extra text.
        I’m kinda curious now what the "easier" method was.

        PS your site rocks! I’d pay for this in book form if I had the money x.x(hopefully learning C++ will solve the money problem)

        • Alex

          He didn’t call writeAnswer(), he just did it all within main().

          Which is totally legitimate, just missing the point of the exercise. 🙂

  • brandon

    thx for the tutorial, it really helps

  • Allen01

    Show me what I’m missing. Why don’t you need to declare “int y” as part of the “int ReadNumber()” function? It would seem that this is necessary since in the main function, both “int x” and “int y” are called. How can “int y” be called if it has not been expressly declared? When the function “int ReadNumber()” was declared at the top of the program, only “int x” was included as part of the declaration. Please explain.

    • Hmmm. When we say “int x” or “int y”, we’re telling the program that we’re defining a new variable, and we’re telling the program what type the variable is and what it’s name is. When a new variable is declared inside of a function, that variable’s name is only meaningful within that function. As a result, it is perfectly permissible to reuse the same variable name within multiple functions. This does not imply any kind of linkage between these variables.

      Within main(), we declare two variables: x and y. These variables only exist within main(). We need two variables here because we have to hold two inputs.

      Within ReadNumber(), we also declare one variable named x. This x has no relationship to the x we declared within main(). In fact, ReadNumber() doesn’t even know that another variable with the same name exists within main(). This is a good thing because it means we don’t have to worry about naming collisions.

      We do not declare a variable y within ReadNumber() because ReadNumber() only needs one variable to do it’s job. Once ReadNumber() is finished executing, it passes it’s value back to the caller (main()). Main() then assigns that value to one of the variables it declared.

      It might help you understand conceptually if you rename the x variable inside of ReadNumber() to “z”, or some other name that is not reused by main().

      • Allen01

        Got it, thanks.

      • Brian

        “When a new variable is declared inside of a function, that variable’s name is only meaningful within that function.” Hi, I probably missed it but was this explicitly stated earlier in the tutorial? I also missed this completely…

        “Main() then assigns that value to one of the variables it declared.” Presumably in sequence?

        “what it’s name is” its name - sorry, born to be a grammar cop.

        Thanks very much for this tutorial.

  • Allen01

    About the function “void WriteAnswer(int)” in question 1):

    Since in the main function, the statement:

    WriteAnswer(x+y);

    does return a value for the addition of x plus y , why does “WriteAnswer” have a type of “void”? Can you provide more clarity on when a function can be of type “void” and return a value such as it does in this case?

    Thanks

    • WriteAnswer() actually does not return anything. When the program reaches the WriteAnswer(x+y) line, the first thing that happens is that x+y is evaluated and resolved to an integer. After that happens, then WriteAnswer() is called. The value of x+y is passed as a parameter of WriteAnswer(). This is why WriteAnswer has a parameter of type “int” -- because the caller is passing it a parameter of type int. WriteAnswer() doesn’t return anything back to the caller, which is why it has a return type of void.

      • Brian

        Hi Allen & Alex. Again, I had the exact same confusion as Allen. Thanks guys.

      • BobZ

        Hi, Alex

        I have been struggling with the first quiz question for more than a week (I have not cheated by viewing any of the answers) and now I am even confuseder by your January 20 2008 explanation here.  You are saying that WriteAnswer does not return anything, but the value of x+y is passed as a parameter of WriteAnswer.  That seems contradictory.  What is the difference between passing and returning? (I don’t think we are discussing football.)  I have to laugh so I do not cry.

        • Alex

          You should re-review the material covered in lessons 1.4 -- A first look at functions and 1.4a -- A first look at function parameters and arguments.

          In short:
          * passing in = the caller sending data to the function via arguments and parameters.
          * returning = the function returning data back to the caller via the return value.

          WriteAnswer’s job is to print stuff, but it needs to know _what_ to print. So WriteAnswer is declared with a parameter, allowing the caller (in this case, main) to pass in data to it via an argument. WriteAnswer doesn’t need to return anything back to the caller (main), so it has no return type.

          ReadNumber’s job is to get something from the user. ReadNumber doesn’t need anything from the caller (main) so it has no parameters. However, after getting a value from the user, it needs to return this to the caller (main). It uses a return value to do so.

          Make sense?

          • BobZ

            Thanks a lot, Alex
            Wow I thought I would never sort out this one…….but my code for the first question ran on first attempt with no errors.  I think the key was that I made up a variable name "karkle" for readNumber 🙂  Now I need to start on the second question; give me another few weeks.  🙁

  • Chad Bernier

    I made a few changes to this program. I took the asking for a number part out of the ReadNumber function, so that i can ask for a first and second number explicitly. I also had the program print the word OK after the user entered a number. Throughout this tutorial, I have been observing the effects of typing in numbers, letters, and even expressions, when it is expecting an integer. You have yet to explain what it does in these cases or how to validate proper inputs. I usually validate inputs in my programs. This is my first low-ish level language, usually deal with higher stuff like MATLAB. I’m sure this all will be explained in later sections. I want to tell you what happens though.

    I enter the letter s for the first number. it prints OK to the screen, since there isn’t any validation, it always does. It asks for the second number. But it answers itself with the word OK, and prints the answer as 0. How does s + OK equal 0? we should clear the input buffer every function then?

    • Chad, I’m just starting to write the sections on I/O (chapter 13), where I will discuss I/O in more detail. Unfortunately, there is no easy way to do numerical validation in C++ when using the standard I/O operators (at least that I know of). As you’ve noted, the >> operator does funny things when the user input is not formatted as expected. There are some other functions that perform more consistently, which I will cover in chapter 13.2 (which should be up sometime this week).

      However, perhaps the best way I’ve found is to read everything into a string, because a string will treat numbers, letters, and whitespace uniformly. Then, you can parse the string to see whether it meets your validation criteria. However, this is somewhat beyond the scope of these introductory tutorials.

  • John

    I am trying to wirte a simple program using on Function, but I am getting following error about stdafx.h.
    Please let me now where I am making mistake.

    fatal error C1083: Cannot open include file: ‘stdafx.h. I will appreciate your help.

    • stdafx.h is a file that Microsoft Visual Studio expects to be the first line in all of your .cpp files. For each .cpp file in your project, make sure you include stdafx.h.

  • Ralph

    I did the first one and to test it I tried compiling it, and at first i thought i was doing something wrong but I can’t compile your code either, I can run it though, and it prints out the solution as expected. I figure I must have forgot something?

    • If you’re running the code, then it’s getting compiled. If you try to run the code when it hasn’t been compiled, the compiler should automatically compile for you before running.

      • Ralph

        mmmm I found the problem, I was using “void Readnumber()” instead of int and somehow when i copied the solution code I did the same thing on the solution. So much for

        Thanks for the timely response though, and your guide is already helping me get ahead of school which is much appreciated.

  • Stuart

    I can’t get solution 3 to build.

    This is my main ccp (test8.cpp):

    This is my io.cpp:

    And this is my io.h:

    This is the error I get:

    c:vcpp2008projectstest8test8io.h(8) : fatal error C1070: mismatched #if/#endif pair in file ‘c:vcpp2008projectstest8test8io.h’

    (I’m putting #include iostream with at each side or iostream at the top of io.cpp here and there isn’t supposed to be space between the << after the cout in io.cpp here either, but it won’t display correctly. Slashes won’t show up in the error message either.)

  • John

    Good job on chapter 1. I’ve really been struggling with stuff like pointers and arrays so I’m going through this whole tutorial slowly. Hopefully the advanced stuff will be as good as this. Thanks for the tutorials!

  • Arocalex

    Can I just put what you have in io.h in stdafx.h? Would that not remove some of the difficulty?

    • Stdafx.h should be used only for stuff that is very unlikely to ever change. Typically stdafx.h #includes other header files that meets this criteria.

  • Vikram

    Very useful!!

  • Ben

    Hi Alex,

    For Problem 1, I actually used 3 “.cpp” files (main, readnumber and writeanswer) and created a header file to make the link. Everything is fine except (yeah I wouldn’t spam this blog if everything were really fine) that it doesn’t compile when I define WriteAnswer() this way:

    #include "stdafx.h"
    #include <iostream>

    void WriteAnswer(int x)
    {
    using namespace std;
    cout << "The sum is: " << x << endl;
    }

    You did that in chapter 1.8.
    The error message I get:

    ---- Build started: Project: Addition, Configuration: Debug Win32 ----
    Compiling…
    WriteAnswer.cpp
    c:\documents and settings\ben.beni\mes documents\visual studio 2008\projects\addition\addition\writeanswer.cpp(7) : error C3872: ‘0xa0’: this character is not allowed in an identifier
    c:\documents and settings\ben.beni\mes documents\visual studio 2008\projects\addition\addition\writeanswer.cpp(7) : error C2065: ‘cout ‘ : undeclared identifier
    Build log was saved at “file://c:\Documents and Settings\Ben.BENI\Mes documents\Visual Studio 2008\Projects\Addition\Addition\Debug\BuildLog.htm”
    Addition - 2 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    But it does compile if I just ask for the output

    cout << x << endl;

    Another question I’ve got, when I run this through Visual Studio 2008, it automatically pauses after it gave me the answer, asking me to press a touch to continue. But if I run that from the “.exe” created, it won’t stop and closes the window right after I enter the second integer (and press enter). How come?

    Thanks.

    • I am a bit perplexed as to why it won’t compile for you. I copied your code into a WriteAnswer.cpp and it worked fine for me. Your error messages don’t make any sense for the code you copied above. Character 0xa0 is the ‘á’ character. You might look through your files and see if somehow one of your ‘a’ characters is actually an ‘á’ instead.

      As for the pausing issue, Visual Studio intercepts the program’s termination and holds the output window open until you hit a key. This is a nice feature that it provides. When you run your program directly from the .exe, it exits immediately upon termination because that’s what it should do under normal circumstances. 🙂

      • Ben

        That’s really weird. I managed to target the annoying part:

        Because if I just ask for the value of “x”, it will work. So it probably doesn’t depend on the rest of my code.
        I know my laptop keyboard is a bit messed up. It’s a Dell laptop with an English keyboard that they re-programmed (or just set up I don’t know what they did) in French. Ridiculous, nothing else but the basic keys (letters & numbers) correspond to what I press. Could it be a reason?
        For example, I know I can’t print the code properly on your website even if I use the appropriate commands. It’s going to work this time because I used a different computer. Really weird.

        Thanks for your help.

        • Ben

          Nevermind, I finaly managed to make it work. Nothing was wrong, so I don’t really know what happened. Like if there was a mysterious character on that line that I couldn’t see.

  • Luciana

    I can’t get quiz 3 answer to compile. I use Code::Blocks 8.02. I copied and pasted exactly the same code from your post, and it gives the following error:

    obj\Debug\main.o||In function `main’:|
    C:\temp\CBProjects\IO_Separated_Files\main.cpp|5|undefined reference to `ReadNumber()’|
    C:\temp\CBProjects\IO_Separated_Files\main.cpp|6|undefined reference to `ReadNumber()’|
    C:\temp\CBProjects\IO_Separated_Files\main.cpp|7|undefined reference to `WriteAnswer(int)’|
    ||=== Build finished: 3 errors, 0 warnings ===|

  • Seltox

    I was struggling with the first question a bit, so I had a look at the answer. I didn’t really understand how it worked, but after compiling it myself, I figured it all out.

    I’d have never thought to write it like that 😛

  • I just want to say thank you, again, for all of this wonderful-ness!! 🙂 The comments are great, too, for troubleshooting my work/problems and for avoiding problems in the future. I love this tutorial. I am an absolute beginner and I’m finding it fairly easy to grasp.

  • daniel

    alex should be nominated as “best man on the net”. this guy like responds, AND COMPILES, everyones problems lol. thanks allexxxx!

  • sami

    Hallo alex,

    I am practicing c++ under Linux ubuntu. till yet i compiled my files in the console with the g++ command. but now i dont know how to compile multible files that belong to one projekt. please is there any sugestion for me ?

    • If I remember correctly from my college days, I believe you can just type the names of all the files you want to compile:

      g++ foo.cpp goo.cpp doo.cpp -o runme

      Once you get into bigger projects, you may want to learn how to use makefiles (or maybe ant). Or easier, move to an IDE environment.

  • PoisonedV

    Whats the point of

    I understand it’s a headergaurd, but I don’t get what defining IO_H does

    nevermind, i didnt see that last #endif and i get it now

  • Tony

    How does main.cpp know to include io.cpp if there’s no include statement for it?

  • Karan

    I made this code for the first question and this code also works.
    But I wanted to know if my code is fine or not.

  • Julian

    Well I managed to do question 3 on my own, however I needed help on 2 and especially 1 😛

    I keep forgetting when and when not to use a semi colon when declaring/defining functions :S

    Also, it gets a bit confusing in the first answer where the ‘int x’ in the “WriteAnswer” function isn’t the same ‘x’ as in the “ReadNumber” or “main” functions…

    I would suggest changing it to ‘t’ or something (t for total)

  • 19bk87

    Hej Alex Admin, another question:

    I took the innitiative to make a slightly different program after completing this test. But guess what? It doesn’t work. I will post the code because I can’t seem to figure it out.

    the main cpp:

    the add and subtract cpp:

    the add and subtract header file:

    error codes:
    1>c:vs2005evencreatiefevencreatiefevencreatief.cpp(8) : error C2660: ‘add’ : function does not take 0 arguments
    1>c:vs2005evencreatiefevencreatiefevencreatief.cpp(9) : error C2660: ‘add’ : function does not take 0 arguments
    1>c:vs2005evencreatiefevencreatiefevencreatief.cpp(10) : error C2660: ‘sub’ : function does not take 0 arguments
    1>c:vs2005evencreatiefevencreatiefevencreatief.cpp(11) : error C2660: ‘sub’ : function does not take 0 arguments

    Thanx for looking it at, hope you see where I went wrong, I really like your tutorials, they make me learn a lot!

    • Code questions about what went wrong with your program are really better suited to be posted elsewhere.

      In this case though, the answer looks easy -- your prototyped functions in addsub.h do not match the ones you declared in the .cpp files. The ones in the .cpp files have no parameters.

  • Leonora A Quarcoo, US

    my question is is it possible to declare x and declare y
    before he main function or i can only declare ReadNumber only once like this

    • Alex

      This program won’t compile because you’ve got multiple definitions for both functions ReadNumber() and WriteNumber().

      Remember that variables declared in a function are local to that function -- the x and y you’re declaring in main() are different than the ones in ReadNumber() or WriteNumber().

  • Corey

    I don’t quite understand the point of having the “io.cpp” file if I use an “io.h” file with the functions declared there instead.

    What I did at first was to use just the two files io.h and main.cpp.

    My io.h file looks exactly like the example io.cpp file minus the

    which I took out because it’s called before the io.h file in my main.cpp file.

    My main.cpp looks exactly the same. This works fine.

    So why do I need to move the contents of io.h to io.cpp and put the forward declarations in io.h? It doesn’t seem necessary and it adds an extra file.

    Hope that’s easier for you to read than it is for me. 😉

    • Putting your code in the .cpp file isn’t strictly necessary with these short little programs. However, it IS a good idea to do it anyway because once you get farther along (especially once you get to classes) you’ll realize that putting code in the headers really clutters up your headers and makes it hard to figure out the structure of your program.

      Furthermore, if you put code in the headers and then have to change that code, you’ll have to not only recompile that header, but everything that includes it too. That means one little change can have a cascading effect on what needs to be recompiled, which can really slow down compilation times.

      So even though it’s not necessary now, it’s good to get in good habits now so you don’t have to break bad habits later. 🙂

  • Chris

    hi, i answered and understood question 1, but when i split the functions into main and io.cpp for the forward declarations of ReadNumber() + WriteAnswer(), getting compile errors all over the place.
    First split Main as in the tutorial…
    Then added io.cpp into source file….
    get the following errors
    \projects\io\io\io.cpp(10) : error C2871: ‘std’ : a namespace with this name does not exist
    \projects\io\io\io.cpp(11) : error C2065: ‘cout’ : undeclared identifier
    \projects\io\io\io.cpp(13) : error C2065: ‘cin’ : undeclared identifier
    \projects\io\io\io.cpp(19) : error C2871: ‘std’ : a namespace with this name does not exist
    \projects\io\io\io.cpp(20) : error C2065: ‘cout’ : undeclared identifier
    \projects\io\io\io.cpp(20) : error C2065: ‘endl’ : undeclared identifier
    1>Generating Code…
    1>firstown2 - 6 error(s), 0 warning(s)
    ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

    then i tried commenting out ‘//#include “stdafx.h”‘ in io.cpp

    and i get….

    \projects\io\io\io.cpp(24) : fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include “stdafx.h”‘ to your source?
    1>firstown2 - 1 error(s), 0 warning(s)
    ========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

    dont understand what is going on here, all I did was split the files as in question 2, now it doesn’t work.

    Please help me to understand, as I cant move on until I do.

    • You need to include the following in io.cpp:

      Also, since you’re using Visual Studio, make sure that stdafx.h is the very first include.

      • BobZ

        Hi, Alex

        I am fighting now with question 2.  You say above:

        "You need to include the following in io.cpp:……."

        I just discovered that.  Does "#include <iostream>" need to be included BOTH io.cpp and main.cpp?  I thought that instructs the preprocessor.  Do we need to tell it twice?  Or can I omit it from main.cpp? (I still have other errors so it is not easy for me to try a controlled experiment.)

        Thanks,

        BobZ

  • Andre

    Just a heads up on the quiz three thing. I was unable to compile the code because my header file didn’t contain

    Or id get an error stating something along the lines of: unresolved symbol something yadda yadda…

  • Kevin

    Question on linking .cpp files: I was unable, for question 2, to link the main.cpp with io.cpp. When I finally tried changing io.cpp to io.h, and left it in the same folder, it suddenly worked. I am using microsoft visual c++ 2008. I am wondering if there is a problem with #including .cpp files in .cpp files. By the way I love your site!

    • Generally it is inadvisable to include .cpp files in other .cpp files, as it’s easy for a .cpp to get included twice that way. for example, if A.cpp includes B.cpp, B.cpp may get included once from A.cpp and again by the project itself.

  • Mike

    Not sure what I did wrong. It compiles just fine. But when I enter the two numbers, I get random asnwers.

    • Alex

      There are multiple problems here:
      1) Inside of Read(), you’re declaring variables x and y. These are local function Read() and get destroyed when the call to Read() is finished.
      2) You can’t mix a call to cout with a call to cin.
      3) On line 20, you’re printing the address of the function Write, not actually making a function call to Write(). Don’t forget that function calls need a parameter list, enclosed in ().

  • Blackshire

    I am terrible at this, just terrible. Time to start from the beginning.

    • csvan

      Dont sweat it, it takes time sometimes. I started coding about 4 years ago and have been doing it to and fro. I am aiming to be a proffesional programmer after college, but I still have a long way to go!

  • Brian

    I can’t even get this to work on Visual Studio Express 2008. Is it me or is there a glitch?

  • Grelf

    Thank you for these great tutorials! I’m really enjoying all of this. :]

  • Mohamad

    I wrote a different set of code where WriteAnswer() calls ReadNumber() twice in a sum operation

    The main function only calls WriteAnswer() one time and the program works fine.
    What I would like to know is how to be able to make the program print the return value for ReadNumber() the return is return(x);

  • amrcidiot

    Thanks so much for your help with learning this.
    I could not have gotten interested without this website.

  • FuturePixstar

    kinda curious about something, when i tried this i tried

    kinda curious as to why WriteAnswer(ReadNumber(nX,nY)) does’nt work. When i look at it i see ReadNumber returning the value of nX + nY into WriteAnswer(int x). I know how to do this problem another way that works just still curious about this. plz and thx you 🙂

    • SkinnY

      /*Looks like you’re trying to multiply(*) integer nX and integer nY, but you failed to tell ReadNumber to do so.
      ReadNumber(nX,nY) should look like --> ReadNumber(nX * nY).
      /*

    • Alex

      Your problem here is that WriteAnswer() returns void, and you’re trying to pass that to cout.

      If you update your last cout line in main() to the following, it will work:

  • Jaredvcxz

    When I try to build the first program, I get an error (Cube::Blocks) saying “expected initializer before ‘int’ on line 8.

    Code:

    #include 
    #include “add.h”
    
    using namespace std;
    
    int add(int x, int y)
    
    int main() // This is the line that had the error
    {
    cout <> x;
    cout <> y;
    
    add(int x, int y)
    
    }
    

    Looking at the other comments, my code is way off and barely complete, but I should at least get this solved for future reference, right?

    • SkinnY

      “int add(int x, int y)” is a forward declaration, which require a “;” at the end of.
      The error was found in line 8 because it was expecting itself to be part of a prototype function, waiting for a {, causing the compiler to complain.

      Your code doesn’t look too bad, but you should break it down some more.

  • Arlis

    Hi Alex,
    Great tutorial. Is there a general rule for when to define a function with parameters or not? I’m a little fuzzy in that area.

  • Andreas

    Am I right, that in the 1’st Quiz, a

    must also be added to our

    ???

    Edit: BLEH! Stupid me. It’s void, not int :p

  • Anon

    Is this correct?

    • SkinnY

      Your int WriteAnswer prototype function should be above main. //Because when WriteAnswer is called in main(), it will not know what you’re referring to yet.
      Also in your main function, “WriteAnswer(num1, num2)” should be “WriteAnswer(num1 + num2)”.//Without adding a symbol in there the variables will not give an argument.

    • Alex

      You never call ReadAnswer().
      WriteAnswer() also doesn’t do any outputting. It just adds two values. In this case, WriteAnswer() would be better named add().

  • Hey there…this is my first night on here, so beginner on c++ eh. But I thought I did everything correctly, but I am stuck with 1 error.

    LINK : fatal error LNK1561: entry point must be defined

    Here’s my 3 files:
    =============================================================================================================
    io.cpp:

    #include
    int ReadNumber()
    {
    using namespace std;
    cout <> x;
    return x;
    }

    void WriteAnswer(int x)
    {
    using namespace std;
    cout << "The answer is " << x << endl;
    }
    =============================================================================================================

    io.h:

    #ifndef IO_H
    #define IO_H

    int ReadNumber();
    void WriteAnswer(int x);

    #endif

    =============================================================================================================

    main.cpp:

    #include "io.h"

    int main()
    {
    int x = ReadNumber();
    int y = ReadNumber();
    WriteAnswer(x+y);
    return 0;
    }

    =============================================================================================================
    I do think this is the best tutorial, I unbookmarked some others just because they were not nearly as useful as this…

    Much Thanx,
    Nick M.

    Forgot to tell you I’m using V.S. 2008…if that helps any.

    • SkinnY

      Your io.cpp needs #include heading it, because you are calling functions that require that library.
      You’re not taking in a value from your int ReadNumber() function, so the compiler does not know where to start at.
      /*BTW, that function should look like:

      /*

    • Alex

      It sounds like maybe your main.cpp isn’t being compiled. Make sure it’s added to your project properly.

  • wesley

    first of all thanks for this site, I really appreciate the step by step help.

    My first thoughts when attempting the quiz was “how do i get WriteAnswer() to use the results from ReadNumber()…
    Also I would have never thought that ReadNumber() could define only x and be used like this inside main.cpp
    So i had to cheat to understand how to accomplish quiz 1.

    quick question i got from the above responses. Is using

    when using cin or cout ok?? I notice other have posted doing this.
    Again thanks for the site, I am a total beginner but I can now see my goal of creating a task/timekeeper for work might actually be possible.

    edit to the above poster i am jsut guessing but maybe your io.cpp

    should be

    but I am guessing

  • That void function is tricky. I worked around it by asking the user for two inputs with different variables and then add them. It works as well, but it wasn’t the assignment.

    • I see the benefit now! There’s just one function that deals with the user input, in stead of asking input for every variable.

      If I add another variable to main, it will ask for a third input automatically.

  • jason

    Funny, everyone seemed to be stumped by the same thing I was, the fact that WriteAnswer only had one int but main had two. Before reading posts about this or continuing with the test, I went back to the section on functions and figured it out, but this was a very tricky question to put on the test, since your examples were all (a,b) in both “main” and the “add” and “multiply” functions. I think you should go back to that section and add a blurb about the relationship between main and external functions, because though it all makes sense once you figure it out, this leads to unnecessary head-scratching for us fledgling coders. You could write a pared-down version of your response in an earlier post:

    “Hmmm. When we say “int x” or “int y”, we’re telling the program that we’re defining a new variable, and we’re telling the program what type the variable is and what it’s name is. When a new variable is declared inside of a function, that variable’s name is only meaningful within that function. As a result, it is perfectly permissible to reuse the same variable name within multiple functions. This does not imply any kind of linkage between these variables.

    Within main(), we declare two variables: x and y. These variables only exist within main(). We need two variables here because we have to hold two inputs.

    Within ReadNumber(), we also declare one variable named x. This x has no relationship to the x we declared within main(). In fact, ReadNumber() doesn’t even know that another variable with the same name exists within main(). This is a good thing because it means we don’t have to worry about naming collisions.

    We do not declare a variable y within ReadNumber() because ReadNumber() only needs one variable to do it’s job. Once ReadNumber() is finished executing, it passes it’s value back to the caller (main()). Main() then assigns that value to one of the variables it declared.

    It might help you understand conceptually if you rename the x variable inside of ReadNumber() to “z”, or some other name that is not reused by main().”

  • lsandling

    Thank You Jason for your explaination…that really worked for me

  • luke

    hey, great site 🙂
    im using visual c++ 2008

    i keep getting this error:
    1>---- Build started: Project: Firstquiz, Configuration: Debug Win32 ----
    1>Compiling…
    1>Firstquiz.cpp
    1>Linking…
    1>Firstquiz.obj : error LNK2019: unresolved external symbol “void __cdecl WriteAnswer(int)” (?WriteAnswer@@YAXH@Z) referenced in function _main
    1>Firstquiz.obj : error LNK2019: unresolved external symbol “int __cdecl ReadNumber(void)” (?ReadNumber@@YAHXZ) referenced in function _main
    1>C:\Users\luke\Documents\Visual Studio 2008\Projects\Firstquiz\Debug\Firstquiz.exe : fatal error LNK1120: 2 unresolved externals
    1>Build log was saved at “file://c:\Users\luke\Documents\Visual Studio 2008\Projects\Firstquiz\Firstquiz\Debug\BuildLog.htm”
    1>Firstquiz - 3 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    any ideas what i can do to fix it?

    • Alex

      Since this is a linker error and not a compiler error, it looks like the definitions for WriteAnswer() and ReadNumber() are missing. My guess is that you probably forgot to include io.cpp in your project.

  • Is it possible to return two integers with one function?
    If so, please demonstrate how. Thanks.

    • SkinnY

      • Alex

        Nice try, but this doesn’t work.

        There are a few different ways to return multiple values from a function, but they require more explanation than is appropriate for a tutorial on basic concepts. 🙂

  • Didier Akara Ndeh

    Using the void is tricky.
    Kaonashi did just as I did and it worked quite well.
    I noticed that Alex’s code doesnt read the second input but simply prints the answer (the sum) immediately you input the second variable.
    They both work anyway!
    Thanks Alex.

  • shreevidya

    i can’t get the solution of this programme.

    my main.cpp is

    int ReadNumber();
    void WriteAnswer(int x);

    int main()
    {
    int x = ReadNumber();
    int y = ReadNumber();
    WriteAnswer(x+y);
    return 0;
    }

    io.cpp is

    #include “stdafx.h”
    #include
    int ReadNumber()
    {
    using namespace std;
    cout <> x;
    return x;
    }

    void WriteAnswer(int x)
    {
    using namespace std;
    cout << "The answer is " << x <

    error is

    LINK : warning LNK4067: ambiguous entry point; selected ‘mainCRTStartup’
    1>main.obj : error LNK2019: unresolved external symbol “void __cdecl WriteAnswer(int)” (?WriteAnswer@@YAXH@Z) referenced in function _main
    1>main.obj : error LNK2019: unresolved external symbol “int __cdecl ReadNumber(void)” (?ReadNumber@@YAHXZ) referenced in function _main
    1>C:UsersSanjayDocumentsVisual Studio 2008Projectsjyocpp programmingquiz1.11bDebugquiz1.11b.exe : fatal error LNK1120: 2 unresolved externals
    1>Build log was saved at “file://c:UsersSanjayDocumentsVisual Studio 2008Projectsjyocpp programmingquiz1.11bquiz1.11bDebugBuildLog.htm”
    1>quiz1.11b - 3 error(s), 1 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    i can’t correct this error.pls give some idea.

    • SkinnY

      Your two prototypes are very messed up.
      Your int ReadNumber() should look like:

      And your void WriteAnswer(int x) should look like:

  • dayana

    At first, Thanks a lot for your wonderful and descriptive tutorial. It’s really amazing!
    I use Turbo c++ 4.5 (windows version) for writing c++ program(My computer is so old and I can’t install visual studio on it). I write 3 piece of code as you said:
    (1)main.cpp

    (2)IO1.cpp

    (3)IO1.h

    I saved IO1.h in INCLUDE directory. but I don’t know what should else I do?!! There’s no place in tc4.5 like visual studio to add another file to my previous project or I don’t know where it’s. When I compile my main there are these errors :
    Linker error : Undefined symbol WriteAnswer(int) in a module MAIN.CPP
    Linker error : Undefined symbol ReadNumbera(int) in a module MAIN.CPP

    • No real problem here, you only forgot to add your namespaces in, well… everywhere.

      • dayana

        Thanks for your reply. but the problem is that I can’t use “using namespace std”. If I put this phrase in my program I will get an error. I can compile and run my program without this phrase easily!!

    • BornToCode

      The reason why you cant use namespaces is cause your using the iostream.h header, instead try using the iostream header (iostream.h and iostream are two different header files), than use namespaces, Hope this helps.

    • day0

      Hey dayana,

      Yeah, I was breaking my head over this for a bit now (And to think I’m revising C++ here. First time at headers though).

      What I did is this:
      1) Go to Start -> Run -> Type “cmd” (without the quotes.
      2) The Command Prompt should open.
      3) Navigate your way to where your code is.
      4) Enter the folder where your code is stored.
      5) If your program is named “BLAH.cpp”, just type BLAH and press Enter.

      The Command Prompt seems to include your file automatically.

      Do let me know if it works.

  • trevie

    hmm i couldnt do question 1 on my own, so i copied out your code in the answer, but it just flashes and goes away, i tryed putting in
    system (“pause”); and stuff, but it still aint working for some reason :/
    using DevC++
    thanks

  • adeyemi

    i am really grateful for this wonderful tutorial, your response to people’s question has answered mine.
    Kiitos!! it means thank you in finnish

  • Cyrus

    Wow, I did it. Thank you so much! The only problem being the site loads up very slow sometimes :[ I understand this is because of how many people are there, but it’s lame :[[

  • Luke

    Alright Alex?

    Loving the guide so far, it’s really well written and very helpful and i’ve had no problems up untill now.

    But i was wondering, is it bad that i couldn’t figure this out?

    I spent nearly two hours trying different things, but didn’t really get close to figuring it out, the only thing i managed to do was build a program that did the same thing but didn’t obide by your rules.

    But my question is, should i really know how to do this problem by now? Is it a bad thing that after me seemingly thinking i learned everything so far in your tutorial, i couldn’t put the pieces together and figure out this problem? 🙂

    • Alex

      Writing your own code is hard, and takes practice. I suspect many people will find this quiz challenging, because it’s asking you to synthesize knowledge that you’ve been presented over many lessons.

      It’s okay if you are unsuccessful, so long as you follow up and understand why the provided answer works.

      One additional good way to learn is to try and extend the program. For example, can you make it add 3 numbers?

  • kun

    Thank you alex sir…. Excellent tutorials….

  • MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

    why do i get this error whenever i type the code out myself, i have compared every little tidbit of code and i still get this… any help?

    • Also when doing problem #3 when trying to write the header guards it shows up that the directive is missing for #ifndef and it doesnt even recognize #endif

      i dunno what im doing wrong 🙁

    • Alex

      Sounds like you’re missing a main() function. Either you forgot to include it, or it’s not being compiled into your project.

  • james

    great and xplicit presentation, wonderful lessons, superb back/follow up quiz. this is just it.
    THE BEST FREEEEEEEEE!!!! C++ TUTORIAL
    THANKS ALEX, U’RE GREAT.

  • matthew

    I’m having a problem, and I’m not sure what exactly is going on. I need to have #include “io.cpp” in my io.h file for my program to work. I’m not sure if that’s the way it should be, or if I made a mistake and that #include “io.cpp” is just shunting around the mistake. Here’s my code:
    main.cpp

    io.cpp

    and lastly, my header file, io.h:

    I know this site went up a while ago, but hopefully someone still reads the comments. Thanks you!

  • King Bob

    I’m confused, in the main function where you declare

    Is that ReadNumber() a function call or a value? If it’s a value (which I assume) then I don’t see the part where there’s a call to ReadNumber() from main(), so it must be a call? But I didn’t know calls could be used as a variable value though? Has this been covered in a previous section or have I missed it?

    • zingmars

      It’s a function call. He initalizes x (and y), and assigns the value outputted by ReadNumber(); function (which is the number you entered using cin.

  • solidace

    why does this ask for x and y twice.
    Please help.

    #include “stdafx.h”
    #include

    int add(int x,int y)
    {
    return (x + y);
    }
    int ReadNumber()
    {
    using namespace std;
    cout << "please enter an x value" <> x;
    cout << "please enter a y value" <> y;
    return x, y;

    }

    void WriteNumber(int x,int y);

    int main()
    {
    int x = ReadNumber();
    int y = ReadNumber();
    WriteNumber(x, y);
    return 0;
    }
    void WriteNumber(int x,int y)
    {
    using namespace std;
    cout << "your answer is " << add(x, y) << endl;
    cin.clear();
    cin.ignore(255, '\n');
    cin.get();
    }

    • Alex

      Because your ReadNumber() function asks for the user to enter both x and y, and you call the ReadNumber function twice.

      That means you’re asking the user to enter x and y twice.

  • life

    Hi, I just wish to know why we put “using namespace std;” in every function which we use “cout…endl”. Because I wrote it top of the page rigt after “#include ” and it works. Isn’t this more sensible because we do not need to write it for every “cout…end” and isn’t this faster for compiler. I am not sure. I think this is called like global which affect every function.

    Please, alex or anyone and thanks.

  • Nilleh

    This is strange. I did the code and it seemed like it should have worked, but for some reason it wouldn’t recognize #ifndef and #endef. I kept getting this error:
    fatal error C1021: invalid preprocessor command ‘endef’
    So, I checked the solution to see what i did wrong, and it looked pretty similar to what I did. I checked it against the code and copied and pasted their solution into my code, except for on the io.h file. It still didn’t work, even though my io.h file was exactly the same as theirs. I then copied and pasted theirs in, and it worked. There was literally no change from before i pasted it in to after, except that after, it somehow worked. I do not understand D:

    • Nilleh

      I started again from a blank slate, and I see what the problem was. I’m not sure how i didnt notice it, but I wrote #endef instead of #endif.

  • zingmars

    Woosh! Well that wasn’t easy.
    I did the first one a bit differentially than Alex did, but then I noticed that my version was going to be harder to implement in the 2nd one, so I had to rewrite my code a bit
    (what I did was:
    #include
    int ReadNumber(int x); //I knew that I’ll need those later
    void WriteAnswer(int x, int y)

    int main()
    {
    including namespace std;
    int x = 0;
    ReadNumber(x);
    int y = 0;
    ReadNumber(y);
    WriteAnswer(x, y);
    int something; //VS10 closes the program as soon as the instructions end, so I put this in to see the output
    cin >> int;
    return 0;
    }
    int ReadNumber(int x)
    {
    using namespace std;
    cout <> x;
    return x;
    }
    void WriteAnswer(int x, int y)
    {
    using namespace std;
    cout << "The answer is " << x + y << endl;
    }
    (Note that there might be some mistakes, because I did this on fly in the comment box, because I deleted my old code :D)
    )

    And for the 2nd one I had a silly typo, but did guess it myself after all (took me like 20 minutes for this whole thing. Most time was spent figuring out the cryptic compiler messages. I guess I should've planned it out huh?).

    3rd one was ez 1 minute job.

    Anyway, why Header Guard? Why not #pragma once? I mean, it's unlikely that any modern compiler will fail to recognize it or anything…

  • Elena_Konkova

    Could you please give me a hint. I have mostly the same code as yours. When I run it, I can enter two numbers, but then the command line just closes not showing any result.

    #include “stdafx.h”
    #include

    int ReadNumber()
    {
    using namespace std;
    cout <> x;
    return x;
    }
    /*int CalculateResult(int x, int y)
    {
    return x + y;

    }*/

    void WriteAnswer(int Result)
    {
    using namespace std;
    cout << "Result: "<< Result << endl;

    }
    int main()

    {

    int x=ReadNumber();
    int y=ReadNumber();
    //int Result=CalculateResult(x, y);
    WriteAnswer(x+y);
    //return 0;

    }

    • It’s because once the result is printed on the screen, the program receives the command to return 0 to OS, closing the program. To prevent that there are multiple options, however the best one in this case would be adding cin >> x; (or anything you’ve declared before, if you’re not feeling like declaring something new) before the return 0;

  • markgtg

    I’m hoping someone can help. I’m currently on #2 and have the EXACT code in the solution, but getting the following error message:

    Warning 1 warning C4627: ‘#include ‘: skipped when looking for precompiled header use c:\Users\Owner\documents\visual studio 2010\Projects\ConsoleAddQuiz\ConsoleAddQuiz\io.cpp 1 1 ConsoleAddQuiz

    Error 2 error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include “StdAfx.h”‘ to your source? c:\Users\Owner\documents\visual studio 2010\Projects\ConsoleAddQuiz\ConsoleAddQuiz\io.cpp 16 1 ConsoleAddQuiz

    Any ideas what could be causing this? I’m using Microsoft Visual Studio 2010.

    Thanks in advance!

  • FlippA

    Hi there,

    First of all I would like to say thank for the useful website, next I have a question I was wondering is it better to declare the using namespace std within the header file so you only ever call it once? As shown below:

    // -- Define preprocesses -- //
    #ifndef IO_H // -- Header guard -- //
    #include
    using namespace std;
    int ReadNumber();
    void WriteNumber(int x);
    #endif

    Kind Regards

    FlippA

    • Nah, better declare it in each file, because there might be files that don’t need to use that namespace, and it might make your compiler scream in pain.

      • Alex

        A header file is the worst place you can use a using statement, because everybody that includes that header will import the using statement as well.

        It’s best to use the using statements in each individual function that needs them. Or avoid them altogether and use the std:: prefix.

  • Jordan15

    Ok, so i am a noob at C++, and need some help. For the first quiz question i tried putting this

    #include

    main()
    {
    using namespace std; //So cin and Cout can be used

    cout <> x; //Reads number from console and stores it in x
    cout <> y; //Reads number from console and stores it in y
    cout << "Your number is: " << cout << x + y; //Displays final number in console

    return 0;
    }

    But, once I compile it, it ends up giving some random "number" which is not really a number because it has x and c in it, which obviously is not what i was expecting. Some help would really be appreciated.

  • christineharvey22

    I am having a serious problem with getting problems 2 and 3 to work. I’m even copying and pasting exactly into files and I can’t get it to run properly.
    For problem number two I am getting the errors:
    Quiz1.obj : error LNK2005: “int __cdecl ReadNumber(void)” (?ReadNumber@@YAHXZ) already defined in io.obj
    1>Quiz1.obj : error LNK2005: “void __cdecl WriteAnswer(int)” (?WriteAnswer@@YAXH@Z) already defined in io.obj

    Can anyone help me out with this?
    Thank you

    • Make a new project, or use a different compiler, because it seems that you have ReadNumber and WriteAnswer defined somewhere else.

      • Alex

        Is it possible you #included io.cpp instead of .h? If you did, you may have gotten two copies of ReadNumber() and WriteAnswer(): one when your compiler compiled io.cpp, and another when the contents of io.cpp were imported into main.cpp.

  • Cleverlegs

    While this doesn’t look very nice to the human eye, it works very nicely.

    It works for a small program like this, but obviously since I don’t store the user inputs or answer, I can’t use them later on if I needed to

  • clmartinez151

    I recently downloaded Visual Studio Express 2010, and I’ve been having a problem whenever I debug my programs. The programs always compile, but when the command prompt opens, and once the program doesn’t require any more inputs from the user, the command prompt quickly closes and doesn’t allow me to analyze the entire process. Is there something I can do so that I don’t have to place the system(“pause”) statement at the end of each program?

  • BradS

    Hi,
    I’ve been following the tutorials and appreciate the time and effort that has gone into putting them together. I’m using Microsoft Visuall C++ 2010 Express.
    I was attempting to solve quiz 1 but kept getting a lnk 1120 error then I modified my Main function to “int _tmain(int argc, _TCHAR* argv[])” and it ran ok. Only reason I attempted this solution after 2 days of tearing my hair out, trying to get it to run was that this is how the main function is presented when I create a new project.

    Could someone please explain to me:
    + why I need to use a Main function that is totally different to the tutorials; and
    + will I experience similar issues with future parts of the tutorials;
    + Do I need to use a different IDE?

    Thanks

    • Hey Brad. I realize you posted this a year ago, but it’s a pretty high-up comment and I had the same question. Here’s an answer I found on stack overflow: http://stackoverflow.com/questions/895827/what-is-the-difference-between-tmain-and-main-in-c

      In short, _tmain is a macro that the compiler has defined to deal with unicode switching. If you have unicode off, it’s replaced by main, and if you have it on, it’s replaced by wmain, apparently.

      So, if you’re using Visual Studio and you get _tmain, it’s cool to leave it.

  • BradS

    Hi Again,
    In addition to my earlier post, my solution to quiz question one allows entry of the two integers but after quickly flashing the answer, dissapears. I searched through the other posted questions and have tried adding the following lines within my main function but it made no difference:
    + “cin.get();”
    + “cin.ignore();”
    + “getch();”

    Can anyone help with this and provide a bit of an explanation (so I learn from the problem) as to why the solution is required?

    Thanks

  • man316

    My compiler (or maybe linker) gives error unless I put [#include “io.cpp”] in the main.cpp. I’m using Code::Blocks.

    • Tovim

      The same with me:
      The #include “io.h” in the main.cpp
      doesn´t work. The #include “io.cpp” does.
      Ergo: the io.h file is quite obsolete here.
      I am also using Code::Blocks.
      Tovim

    • rameye

      Make sure that you have io.cpp included into your IDE project, or it will not be included in the build and compiled. If io.cpp is not compiled there will be no object file containing the io.cpp functions. Therefore even though you have used #include “io.h” in your main.cpp, the linker will not be able to find the compiled functions. Doing a #include “io.cpp” is not needed and is bad form. Only include .h header files that have the forward declaration prototypes of functions that live in the .cpp file. But it is still your responsibility to ensure that the .cpp files are all compiled when you do the build with your IDE. The bottom line is both main.cpp and io.cpp should be source files included in your IDE project. Then it will all come together correctly when you do the build.

  • sunoy14

    I used the following code for the first question and it worked. Is it ok?

    #include

    int add(int x, int y);

    int main()
    {
    using namespace std;
    cout <> x;
    cout <> y;
    cout << "the sum is :" << add(x, y) << endl;
    return 0;
    }

    int add(int x, int y)
    {
    return x + y;
    }

  • sunoy14

    can you please explain some questions?

    1. why is the return x in the int readnumber() function.
    2. what does void do
    3. how does the void writeanswer(int x) work in this program.
    4. why did we not do anything for int y. Also even we did not call for int y, the program produces
    two numbers and add them up.
    5. How come the program solution asks for number two times even though there is only one readnumber()
    function? Also there is only one cout and cin in the readnumber function. Also only int x was
    declared.

    Thank you

    • Frelion

      1. return x is in that function so it can give the number from the user “x” to be used in main. (it sends/returns the user’s number that they input back to main)
      2. void is used at the beginning of functions to tell main that it won’t return a number.
      3. writeAnswer works because the parameter inside the parentheses gets used in main once main pulls x from the readnumber() function, who told the user to enter a number, in the last answer to the quiz, you can add two numbers together in the parameter for writeAnswer and it will solve it and use the sum as the new number to be printed.
      4. int y was assigned to another readnumber() function, so now you have 2 of those functions and thus 2 new numbers from saved from the user.
      5. There is only one ReadNumber() function, but it was called twice, and using my answer from number 4, you do that to make programming easier and so you don’t have to type as much (or hard-code as much) later on.
      5.Also. because you called the function twice and saved the numbers as different assigned variables in main all the actions of that function happen twice so it once again asks for input.
      5.Also.2. only that x was declared and it was put into a different x and a y in main, it was called twice so you wouldn’t have to type as much.
      Wow, answering these questions clearly are hard… If you are struggling with all that stuff, I recommend that you start over the tutorials up until here until it all makes sense. You need to learn which x is tied to which and what happens if you change the name of your variables in functions vs what you call them in main. Hope it helped, I love these tut’s, thanks!

  • cmastah

    Hi, thanks for the awesome website and the excellent opportunity to learn C++. I wanted to ask:

    1. Why is it that in WriteAnswer(int x) we put the int x within brackets whereas with ReadNumber(), the int x is within the function itself. I tried putting the int x within the WriteAnswer function instead of within the brackets but got errors.

    2. Why is it that when we declare int x and int y in the main() function, that typing them up as “int x = ReadNumber();” actually executes/compiles/starts the function rather than just take it as a declaration of int x. I would’ve thought we’d have to actually type it up as:

    int main()
    {
    int x;
    int y;
    ReadNumber(int x);
    ReadNumber(int y);
    WriteAnswer(x+y);
    }

    When doing them as such, I got a “error: expected primary-expression before int”.

    3. When I do the program as outlined above and instead use “ReadNumber(int)”, I get an error but I’m not sure why.

    4. If we chose to redo WriteAnswer as “int WriteAnswer(int x)” with return 0, it still works. Is there any specific reason we’d go with void over int?

    5. This goes a little further from this specific section, but I’m curious, what is the caller? I would’ve thought the user would be the caller. I ask because void means the function doesn’t return any values to the caller but can return values to a user like in the above function. I still feel myself stumped by void, is there any in-depth explanation I can read on void and its uses?

    • RevEng

      1. Why is it that in WriteAnswer(int x) we put the int x within brackets whereas with ReadNumber(), the int x is within the function itself. I tried putting the int x within the WriteAnswer function instead of within the brackets but got errors.

      The “int x” allows and tells the WriteAnswer function to expect and process an integer called “x” from the calling function (in this case “main()”. Whereas, the empty parentheses “()” tells the ReadNumber function that there is no input being passed (no incoming parameters to process) to the function.

      2. Why is it that when we declare int x and int y in the main() function, that typing them up as “int x = ReadNumber();” actually executes/compiles/starts the function rather than just take it as a declaration of int x. I would’ve thought we’d have to actually type it up as:

      int main()
      {
      int x;
      int y;
      ReadNumber(int x);
      ReadNumber(int y);
      WriteAnswer(x+y);
      }

      When doing them as such, I got a “error: expected primary-expression before int”.

      ReadNumber() returns a value that will be assigned to “x” (or “y” for the second call). When you place “int x” inside the parentheses, you are passing the value of “x” in main() to the ReadNumber() function. This is not valid, since the ReadNumber() function does not accept any parameters.

      So, if you want to give a function a parameter and that function is set up to receive a parameter, put it inside the parentheses-e.g. WriteAnswer(int x). If you are calling a function that doesn’t accept parameters, you leave the parentheses empty-e.g. ReadNumber().

      The reason you received the error is that ReadNumber() function does not receive any parameters. You cannot pass (int x) or (int y) to ReadNumber(). REMEMBER: When you call a function, make sure the number of parameters in your calling function matches the number of parameters the called function expects.

      3. When I do the program as outlined above and instead use “ReadNumber(int)”, I get an error but I’m not sure why.

      See answers to Questions 1 and 2.

      4. If we chose to redo WriteAnswer as “int WriteAnswer(int x)” with return 0, it still works. Is there any specific reason we’d go with void over int?

      Whenever a called function completes, it will return a value. The type of expected return value is stated before the function on the same line.

      For example:
      void WriteAnswer(int x) means that WriteAnswer will return “void”-in other words, nothing-when it finishes doing what it’s supposed to do.

      int ReadNumber() means that ReadNumber will return an “int” or integer when it finishes doing what it’s supposed to do. In this case, the returned value will be the number that the user entered.

      5. This goes a little further from this specific section, but I’m curious, what is the caller? I would’ve thought the user would be the caller. I ask because void means the function doesn’t return any values to the caller but can return values to a user like in the above function. I still feel myself stumped by void, is there any in-depth explanation I can read on void and its uses?

      The “caller” is the name of the function that /calls/ another function. For example: main() calls ReadNumber() and WriteAnswer(x+y)-“main” is the /caller/ and ReadNumber and WriteAnswer are the /called/ functions. If ReadNumber calls another function, such as “cin”, then, ReadNumber is the /caller/ and “cin” is the /called/ function. It’s just a matter of point of reference when using the word “caller” vs. “called”.

      As for the rest of your question regarding “void”, see my answer to Question 4.

      I hope this helps!

  • Angster

    I used this code for #1. I think it’s quite clever.


    /* This is my answer for quiz problem
    * number one. It takes two values from
    * the user, and adds them.
    */

    #include "stdafx.h"
    #include <iostream>

    int ReadNumber()
    {
    using namespace std;
    cout << "Insert the first number to be added:" << endl;
    int add1;
    cin >> add1;
    cout << "Now, insert the second number:" << endl;
    int add2;
    cin >> add2;
    return add1 + add2;
    }

    int WriteAnswer(int sum)
    {
    using namespace std;
    cout << sum << endl;
    return 0;
    }

    int main()
    {
    using namespace std;
    WriteAnswer(ReadNumber());
    /* The above code begins
    * the ReadNumber script,
    * and once the ReadNumber
    * script has completed,
    * sends its return value
    * to WriteAnswer.
    */
    return 0;
    }

  • s.spencer

    i know that my code is more complicated and long winded than it needs to be, but i thought there’s no point doing the quickest way, and then moving on even if i don’t understand. in the following code it doesn’t like the writeAnswer(Z) bit and says “z” is undefined, but if i define in in main() with a value then it just prints out that value…any help please? it’s the only error coming up however i’m also wondering if the rest of the code i’ve done so far is allowed, as i wasn’t even sure if you can use 2 values in the return bit like i’ve tried below.

    #include “stdafx.h”
    #include

    using namespace std;

    int readNumber()
    {
    cout << "Enter 2 numbers to be added" << endl;
    int x;
    cin >> x;
    int y;
    cin >> y;
    return x, y;
    }

    int add(int x, int y)
    {
    int z = x + y;
    return z;
    }

    void writeAnswer(int z)
    {
    cout << z << endl;
    }

    int main()
    {
    int x, int y = readNumber();
    add(x, y);
    writeAnswer(z);
    system("pause");
    return 0;
    }

    • Alex

      z is a function parameter of writeAnswer(), and thus only exists within the scope of function writeAnswer.

      Main can’t see z, nor access it.

      If you defined z like this in your main function:

      it would work.

  • pranesh

    i have just written the same codes but it is showing error and that is
    1>e:\c programs\comprehensive_test_1_add_2_nos\comprehensive_test_1_add_2_nos\comprehensive_test_1_add_2_nos.cpp(32): fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include “stdafx.h”‘ to your source?
    can u tell me what could be possibly wrong?

  • Hello Guys, if you are having problems with Chap1 sec11 quiz, I completed Q1, and it works perfecly!
    #include “stdafx.h”
    #include
    #include

    int ReadNumber()
    {
    using namespace std;
    cout << endl;
    cout <> InputNum;
    return InputNum;
    }

    void WriteAnswer(int FinalResult)
    {
    using namespace std;

    cout << "Your Result is = " << FinalResult << endl;

    }
    int main()
    {
    using namespace std;

    // Get 1st input(number) from user:
    int Number1 = ReadNumber();

    // Get 2st input(number) from user:
    int Number2 = ReadNumber();

    // Calculate the result:
    int FinalResult = Number1 + Number2;

    // Print the result:
    WriteAnswer(FinalResult);

    }

  • Alex, or anyone else can help in explaining why I am getting error for ReadNumber() “function does not take 0 argument” when I forward declare the readnumber as:
    int ReadNumber(int x) i.e int x defined inside the paranthesis; but if I change it to:
    int ReadNumber(); the program complied with success. This change was done for both main.cpp and io.cpp Appreciate your clarification.
    For WriteAnswer(int FinalResult) i had the variable defined inside the parenthasis, but I didn’t get any errors, why only for ReadNumber ??? lost here

    • rameye

      A forward declaration is the function definition without the function body. It tells return type, function name, and the number of and type of the function parameters.

      When you call the function after the forward declaration has been given, the number of parameters in the function call has to match with the number of parameters in the forward declaration.

      So if you change the forward declaration by making it have one argument instead of zero arguments, then you have to also change the function calls to have one argument. For example from int num = ReadNumber(); to int num = ReadNumber(10);

      If you don’t do that and still call the function with 0 arguments the compiler will complain about it. Mis-matched parameter list.

  • adeater

    What does it mean when “[Error] ld returned 1 exit status” ?
    I’m stuck at this point. I don’t know how to link these source files to run the program.
    Even if I copy and paste this exactly the same code from this page it won’t work. I use Dev C++ 5.7.1
    What should I do next to get this program going?

  • David

    Hi guys. Can someone please take a look at these 3 files I’ve created in answer to the third part of this quiz? It works fine without the header file and with a forward declaration, but when I use the header file my console comes up blank. I’m assuming it’s not an issue with main() because when I transfer the cout << "Select 2 numbers to be added together" << endl; from ReadNumber() to main(), the console comes up with "Select numbers to be added together" and then closes if I enter a number and press enter. Thank you in advance!

    • Joseph

      I noticed you didn’t include iostream in main.cpp because you aren’t using anything from std in it, but what if you were?
      Is there a way to include iostream in all .cpp files at once, or do you have to actually include it in every .cpp file separately?

    • Alex

      Your problem is that in main, you’re not calling your functions correctly. Instead of:

      Try:

  • Vishrut

    Thanks Alex for these tutorial

    I am using bloodshed Dev c++

    Cant find answer of Question 2

    io.cpp

    #include
    int ReadNumber()
    {
    using namespace std;
    cout <> x;
    return x;
    }

    void WriteAnswer(int x)
    {
    using namespace std;
    cout << "The answer is " << x << endl;
    }

    main.cpp

    int ReadNumber();
    void WriteAnswer(int x);

    int main()
    {
    int x = ReadNumber();
    int y = ReadNumber();
    WriteAnswer(x+y);
    return 0;
    }

    errors
    - C++ Compiler: C:\Program Files (x86)\Dev-Cpp\MinGW64\bin\g++.exe
    - Command: g++.exe "F:\extra\basics\main.cpp" -o "F:\extra\basics\main.exe" -I"C:\Program Files (x86)\Dev-Cpp\MinGW64\include" -I"C:\Program Files (x86)\Dev-Cpp\MinGW64\x86_64-w64-mingw32\include" -I"C:\Program Files (x86)\Dev-Cpp\MinGW64\lib\gcc\x86_64-w64-mingw32\4.8.1\include" -I"C:\Program Files (x86)\Dev-Cpp\MinGW64\lib\gcc\x86_64-w64-mingw32\4.8.1\include\c++" -L"C:\Program Files (x86)\Dev-Cpp\MinGW64\lib" -L"C:\Program Files (x86)\Dev-Cpp\MinGW64\x86_64-w64-mingw32\lib" -static-libgcc
    C:\Users\HP-I5\AppData\Local\Temp\ccEAgU4O.o:main.cpp:(.text+0xe): undefined reference to `ReadNumber()'
    C:\Users\HP-I5\AppData\Local\Temp\ccEAgU4O.o:main.cpp:(.text+0x16): undefined reference to `ReadNumber()'
    C:\Users\HP-I5\AppData\Local\Temp\ccEAgU4O.o:main.cpp:(.text+0x28): undefined reference to `WriteAnswer(int)'
    c:/program files (x86)/dev-cpp/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/4.8.1/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\HP-I5\AppData\Local\Temp\ccEAgU4O.o: bad reloc address 0x0 in section `.pdata'
    collect2.exe: error: ld returned 1 exit status

    New at learning programming
    please guide.

  • JTD

    Kinda frustrated, i don’t recall being taught how to add things without using a add function. Not one time was it mentioned how, yet it’s asking me to do so. Don’t know what to say about that.

    • Alex

      Use the + operator. Basically, the same as what’s in the body of the add() function we’ve used in many of our examples so far, minus the function parameters.

      • JTD

        God damn, the poor wording you use in the quiz questions, also asking us to do the adding without a add function(which has not been covered at all throughout chapter 1). Has all really screwed me over, along with my motivation now.

        I’m doing it the right way and it just doesn’t work, i even went into the solution, made sure there was nothing wrong and i still get errors like this :

        warning C4067:unexpected tokens following preprocessor directive -expected a newline

        error C2008:’.’: unexpected in macro definition

        • JTD

          finally started working after i remade the entire damn thing and it runs but i still get a error that says

          Error 1 error LNK1168: cannot open C:\Users\Jake\Desktop\IDE STUFF\numberoneee\Debug\numberoneee.exe for writing C:\Users\Jake\Desktop\IDE STUFF\numberoneee\numberoneee\LINK numberoneee

          Really sick of nothing ever working.

          • Aston

            Excuse me JTD, but I personally found these quizzes to be just fine when I did them. Please don’t get so aggressive and hostile, as Alex is writing a helpful guide *for free* and then ALSO continuing to help troubleshoot in these comments!

            If you post the code you’re having trouble with, we might have a better chance at working out what the problem is. Simply getting angry about things and blaming other people for problems will only cause other people to also get angry, or simply ignore you.

            • JTD

              Mmn, i realized later that i was being childish and letting myself become stress and taking it out on others. I do apologize alex for my poor behavior, i popped back on today and manage to do the quiz 1-3 without having to check the website or the solutions. Though i think i may need to go over a couple sections again to get a few things dug in.

  • Derpy Derp

    This is my answer for number 1 but for some reason it won´t compile can anyone of you tell me why?

    #include “StdAfx.h”
    #include

    int readNumber()
    {
    using namespace std;
    cout << "Enter any number you want" <> x >> std::endl;
    cout << "Enter another number" <> y >> endl;
    return 0;
    }
    int writeAnswer(int x, int y)
    {
    using namespace std;
    cout << "Both your numbers added together is equal to:" << x + y << endl;
    return 0;
    }
    int main()
    {
    int readNumber();
    int writeAnswer();
    return 0;
    }

    • Alex

      It’s a bit hard to tell because your code didn’t post correctly, but it looks like:
      1) readNumber() is trying to output text AND input values for x and y on the same line. These need to be separated.
      2) readNumber() is using x and y without declaring them.
      3) main() isn’t calling readNumber and writeAnswer() correctly. Remove the return types.
      4) main() isn’t passing the right number of parameters to writeAnswer().

  • Sergi

    Hi!

    First of all, thank you for the tutorial, it's really helpful!
    Now to my question: I basically understand all your code (it's quite simple) but when I run the program the command-line shell automatically closes right after writing the answer, so I don't have time to read it. Why is that and how can I solve it? (I am using Code:Blocks in Windows 7 64Bits).

    Thank you in advance!

  • Catreece

    Huh… maybe I glossed over it or something, but I didn't see anything before which said that (x+y) could be used as a single (int x) before for a function. That's seriously a handy tool to have, though, since I would've assumed it to be counted as two separate inputs otherwise.

    I can see all sorts of handy uses for such, though… would clean out a ton of excess functions being used for minimalistic work. I can still see times where you'd want to use a separate add function, or to feed x and y into the function and add them internally, but I can also see a lot of use for being able to essentially skip a step occasionally when it's not really needed.

    My first version fed (int x, int y) and then just had the cout list x+y combined without otherwise adding them except for the output itself. After checking up on the answer after the second test (first one compiled and ran just as intended so didn't bother to check =P ), I played around with the feeding in of extra stuff as a singular (int x). I may have sidetracked myself from the test with such exploration… and then started using the if() function to add on more stuff… you know, there's a reason I would often run out of time for tests while in school. XD

    Oh well, it works, and I learned something new. =P

    Thanks again, as usual, for the site and tutorial, awesome as always! Thooouuugh if the combined (x+y) as a singular (int x) thing isn't mentioned elsewhere though, might be handy to put it in somewhere. That's assuming I didn't somehow read over it and just don't remember. The latter's probably more likely, but just in case!

    • Alex

      (x+y) is an expression that is evaluated. For example, lets say x is 2, and y is 3. When (x+y) is encountered, the compiler evaluates this to produce a single value (5). That value can then be assigned (or in this case, passed to a function as a parameter). You may be right that I never showed an example of this. I’ll add one.

      Separate function parameters are always separated by a comma.

  • Evlesoa

    Hi, I love the tutorials. I'd like to ask something, though.

    Why does this here work?

    int readNumber(int get1, int get2)
    {
    using namespace std;
    cout <> get1;
    cout <> get2;
    return get1 + get2;
    }

    int writeAnswer(int total)
    {
    using namespace std;
    cout << "Answer is " << total << endl;
    return 0;
    }

    int main()
    {
    writeAnswer(readNumber(1,1)); // the 1,1 can be replaced with ANY number, but not letters!
    return 0;
    }

    That 1,1 (last line). Why can it be anything but letters? I don't understand this part.

    • Alex

      readNumber takes integer parameters, not numbers. If you pass in letters, what does it even mean to add them together?

      • Evlesoa

        Ah, I understand. So if it takes numbers, and the numbers can be anything, what does it do to them? Does it store the answer in numbers? I can use 0,0, or 1,1, or 999,999, and it all gives the same answer. Can you please explain? Many thanks.

        • Alex

          What do you mean it all gives the same answer?

          Taking a closer look, you’re passing two parameters to readNumber: the numbers 1, and 1, which become parameters get1 and get2 respectively. readNumber prints each of those out individually, then returns the sum to the caller. That sum is then passed to writeAnswer as parameter total, which prints it.

          It’s weird that your readNumber function adds two numbers together and doesn’t do any reading. It’d make more sense if you renamed it addNumbers or something.

          • Evlesoa

            I mean the two parameters to readNumber of 1 and 1 can be any number. Basically, if I wrote readNumber(1234,54321), it will give me the correct output of whatever I write in readNumber when it asked for two numbers (if I add 2+2, it will give me 4 no matter what that 1,1 is changed to).

            I named it "read" because it reads what is being passed to it. Maybe should called it storeNumber instead? Basically, instead of just having it being called twice, I made it so that it's called once. This kind of shortens what you wrote in the tutorial, but it's not the same. You can say that I was experimenting around with it to try to understand what is going on.

            Thanks, tremendously for your explanations, once again. I really hope I can master this stuff.

  • Silvano

    This worked..

    • Alex

      Your readNumber function doesn’t do anything useful (it adds two numbers, but that result is thrown away since the return value isn’t assigned or passed to anything).
      I’m also not sure why both readNumber and writeNumber are adding. Nothing in the names of the function suggest they will add the parameters…

  • Souvik Pal

    Mah answer to Question 1 :

    #include<iostream>
    int readNumber()
    {  
    int n;
    using namespace std;
    cin>>n;
    return n;
    }
    int writeAnswer(int ans)
    {
    using namespace std;
    cout<<"The addition is="<<ans;  
    }
    int main()
    {
    using namespace std;
    cout<< "Enter the first number :"<<endl;
    int x1= readNumber();
    cout<< "Enter the second number :"<<endl;
    int x2= readNumber();
    int ans=x1+x2;
    writeAnswer(ans);
    return 0;
    }
    Is it ok Mr. Alex.

    • Alex

      Mostly correct. Two minor issues:
      * writeAnswer should be void since it doesn’t return a value.
      * There’s no need to use “int ans=x1+x2”. Just pass the expression “x1+x2” as a parameter to writeAnswer.

  • Daniel

    Hello Alex,

    Just a few questions after having completed the quiz and tried some extra bits to further my understanding.

    I have a program that takes 2 inputs from user via one function called twice, it then uses a function to add the two inputs to define a third variable which is then divided using a function & printed using std::cout.

    All functions are defined in seperate .cpp files with a header file containing all declarations. (all compiles correctly)

    I was just wondering about the header files, does one need a seperate header file for each function e.g add.h, divide.h getInput.h.

    It seems it would get really messy quickly having loads of header files for every function. But I can kind of wrap my head around why it may make more sense on huge programs/projects.

    Also, on all of my .cpp’ created it says in brackets (global scope), is this correct in the context of these tutorials?

    I hope my question makes sense.

    kind regards

    Daniel

    • Alex

      Hi Daniel.

      You don’t need a separate header file for each function (as you note, it would get messy quickly). Typically both code files and their header file counterparts are divided into logical groups. For example, if you have a bunch of function to deal with vector math, you might have a vector.cpp that defines a bunch of functions, and a vector.h that includes the prototypes for all of the functions in vector.cpp. That way, if any of your programs need to use the vector functionality, you #include and make sure vector.cpp is compiled into your project, and you’re good to go.

      As for the (global scope), I’m not sure what that is in reference to. It doesn’t sound like anything to be concerned about at this point though.

  • Hey Alex,

    Below you will find the code for a programme I am making just for practice in Xcode. Im up to chapter 1.12 and I need a bit of help with a few things.

    I may be asking a bit too much, but you don’t ask you don’t get.

    - How can make it so that the user can enter a gun name without using a capital letter at the start and still be show the if statement that is linked to it?

    - How can I make it so that each gun has a different minimum bid?

    #include <iostream>

    int main()
    {
        //welcome();
        using namespace std;
        cout << "Welcome to WhichGun?, the home of the best weapons the world has to offer. " << endl;
        
        //whichGun();
        cout << "We have 4 guns up for auction tonight, the names are: Bloco, Remin, Selor, and Sonit. "<< endl;
        cout << "Please type the name of the gun you would like to bid for. (including capital letter) " << endl;
        char word [80];
        cin >> word;

        //commentOnGun();
        string bloco ("Bloco");
        string remin ("Remin");
        string selor ("Selor");
        string sonit ("Sonit");
        
        if (word == bloco)
        {
            cout << "Ahhh so you want to bid for the Bloco Pistol. Wise choice for someone who is looking for a personal weapon to carry around with them. " << endl;
        }
        if (word == remin)
        {
            cout << "There are only 3 Remin Sub-Machs in the world. " << endl;
        }
        if (word == selor)
        {
            cout << "I have one of these myself. It is a very useful hunting rifle. " << endl;
        }
        if (word == sonit)
        {
            cout << "Only those who are looking to cause major damage would purchase the Sonit 104 Launcher. " << endl;
        }
        //howMuch();
        cout << "How much would you like to bid for the " << word << endl;
        int x;
        x = 0;
        cin >> x;
        if (x < 10000)
        {
            cout << "Sorry the minimum bid for any wepaon is £10,000. " << endl;
        }
        else
        {
            cout << "Brilliant take a seat, I will confirm your bid and you will be called to the front if you are the winning bidder. " << endl;
        }
        //thankYou();
        cout << "Thank you for partcipating in the 5th annual WhichGun? auction, Please spread the word and come again next year. " << endl;

    }

  • Meowmeow_Prince

    what the point of using the "Using namespace std;" twice in the io.cpp where you could just put it in the header and have it there for the whole scope of the file because everything there uses it

    • Alex

      The point of declaring “using namespace std” inside of a given function is that we limit the effects of the using statement to just that function. That allows us to get the benefit of the using statement (not having to repeatedly type std::), while minimizing the risk that our code has a naming conflict with something inside the std library.

      Using “using” statements outside of individual functions (_especially_ inside header files) should be avoided, as it significantly increases the chance of having a naming collision with something in the namespace.

  • MD jYa

    where i am wrong,plz tell me???

    • MasterCreator

      In line 14, you’re trying to call the function writeAnswer() in itself. Instead, try the following

  • Dominus

    Wow, i already made this exact program while going through the tutorials! Great work by the way, im really getting into C++ thanks to you!

  • MD jYa

    Thanks to U all for helping me out….Thank U MasterCreator
    Its a Great Tutorial..
    Thank U Sir Alex…

  • inkboy12345

    Hey, this code i wrote works completely fine as far as I can tell, but i’m curious as to whether i’m using any bad form, or wrong/unnecessary syntax (i know i’ve written iostream and stdafx.h twice, because sometimes it gives me weird syntax errors so I put it in there for the sake of paranoia)  

    main.cpp

    io.cpp

    READ_N_WRITE.h

    • Alex

      My suggestions:
      * READ_N_WRITE.h should be named io.h, so that io.h pairs with io.cpp.
      * It’s weird to have writeAnswer read in numbers. I’d call readNumber() twice from main, and pass both the values into writeAnswer as parameters.
      * writeAnswer should be given a better name, like writeSum().
      * Don’t “use namespace std” outside of a function. Put it inside each function that needs it.

      Other than that, seems fine for where you are at this point in the tutorial. 🙂

  • Root

    Hey Alex, can u please explain the "return x" part in an int function. i mean in the previous functions i realized that if we take an input (lets say x), then in the end of the int function we end with "return x". i tried return zero for everything and the whole calculation part went wrong as no matter what,it just assumed 0.
    What if we take more than one input in a function other than main()?what should we end it with?
    also if we expect the answer like 2.5 , what should we include for it to display this number?

    • Alex

      Functions can only return one value, and the type of that value is determined by the return type (which so far, has only been int).

      If you need to return more than one value to the caller, there are ways to do that but none of those are simple, so I don’t talk about that until later.

      If you expect a non-integer return value, then you should use something other than int as your return type. In the next chapter, I talk about floating point types, which are used to handle fractional values (such as 2.5).

  • Marta

    I just wanted to post a thank you message for you. This tutorial is amazing and I feel I’m learning fast and well. Thanks!

  • SS

    how is this peice of code:

    #include <iostream>
    using namespace std;

    int readNumber()
    {
        int a, b;
        cout << "Enter a number: " ;
        cin >> a;
        cout << "Enter another number: ";
        cin >> b;
        return a + b;
    }

    int writeAnswer()
    {
        return readNumber();
    }

    int main()
    {
        cout << "The sum is: " << writeAnswer() << endl;
        system("pause");
    }

    • Alex

      Needs some work. 🙂
      First, writeAnswer actually doesn’t do anything. You might as well just call readNumber.
      Second, readNumber is misnamed. It should be called something like readAndAddNumbers based on the way you’ve written it.
      Third, it’s bad form to use system(“pause”).
      Fourth, it’s bad form to use “using namespace std;” outside of a function.

      But it would really be better if readNumber just read in a single number, and writeAnswer did the writing, and main did the adding of the numbers read in from readNumber. That way your functions each have one job.

  • BobZ

    Hi, Alex:
    I have been fighting with Question 3 for over a week and after try this try that, making no progress.  At present I have 7 errors and 8 warnings.  

    My main.cpp is:

      my io.cpp is:

    and my io.h is

    • Alex

      At a glance, your main.cpp and io.cpp look good.

      It’s your io.h that’s going to give you problems and is probably causing all your errors.

      First off, io.h shouldn’t include stdafx.h or iostream, because it doesn’t need/use either. Header files should only include other headers that they directly reference.

      Second, your header guards are incorrect. Your only need one set of header guards per header file, and everything should be inside the guards. The guards should also be named after the filename as a best practice:

      Third, you don’t need to #define your functions in this way. It doesn’t make sense, and it’s confusing the compiler. Instead, what you want to do here is put your forward declarations:

      That way, when main.cpp (or any other file) #includes io.h, the forward declarations from io.h will be copied into main.cpp.

      I hope that’s helpful.

  • Tyler

    I was none-too pleased when I had to do it over again because I put writeAnswer(readNumber()); and had to have 3 forward declarations to support it.

  • r00kie

    Alex,

    I have been checking your solution for quiz no 1 and I do not understand why the void is like this :

    void writeAnswer(int x)
    {
        std::cout << "The answer is " << x << std::endl;
    }

    If I write your void function like bellow, the program gives me this error :

    error C2660: ‘writeAnswer’ : function does not take 1 arguments

    void writeAnswer()

    {

         int x;

        std::cout << "The answer is " << x << std::endl;
    }

    What’s the deal with int x, and why the program only works if you declare it like this :

    void writeAnswer (int x)

    and not inside the void function ?? inside { }

    with readNumber it goes the other way around, if you try to initialize X like this readNumber(int x) it doesn’t work …please explain why some X gets initialized inside () and others inside {}

    To stay away from things I do not understand, I wrote my code like this and it worked perfectly , but please explain what’s the deal with X and why you have it initialized sometimes in () and sometimes in {}

    As you can see , I am initializing x only inside {} , but I would love to know why you do it sometimes in ()

    int readNumber()
    {
    std::cout <> x;
    return x;
    }

    void writeAnswer()
    {

    int x;

    x = readNumber() + readNumber();

    std::cout << "The answer is " << x << std::endl;

    }

    int main()
    {

    writeAnswer();
    return 0;
    }

  • r00kie

    Don’t worry about the first function in my program "readNumber" , I am not sure why some data didn’t get copied corectly, my readNumber is written correct , like this and it works…just explain to me why sometimes you declare int X inside () , instead of {} and why on your program if you do it inside {} it doesn’t work…

    int readNumber()
    {
        std::cout << "Enter a number: ";
        int x;
        std::cin >> x;
        return x;
    }

    • Alex

      If you put a variable inside the (), it’s considered a function parameter, and the value must be passed in by the caller.
      If you put a variable inside the {}, it’s considered a local variable, and the value must be defined by the function itself.

      In the case of function writeAnswer(), the function caller supplies the value to write, so x must be a function parameter, not a local variable.

      Make sense?

  • r00kie

    Alex,

    Is there any past lesson in the previous chapters where I can read more and understand how the values inside () are passed in by the caller ?

    I understand perfectly how it works inside {} and this is why I sticked to variables inside {} in my program , but I don’t quite understand how the function parameters work inside () ?

  • Joao Lopes

    This is how I solved 5#

    main.cpp

    io.cpp

    io.h

  • Kemikals

    This is how I did it.

  • Aroma

    Hi Alex, below is my answer to each of the 3 questions, everything compiled and linked fine!, Any comment on my code to help me improve?

    (Question 1)main.cpp[
    #include<iostream>
    using namespace std;

    int readNumber()
    {
        cout<< " please enter a number ";
    int a;
    cin>> a;                                 //First user input
    cout << "please enter another number";
    int b;
    cin>> b;                                 //second user input

        return a + b ;
    }

    void writeAnswer(){                      // A function to output the final result
        cout<< "the sum of the two numbers is "<< readNumber() ;}

    int main()
    {
        writeAnswer();
    return 0;
    }]

    (Question 2)io.cpp
    [#include<iostream>
    using namespace std;

    int readNumber()
    {
        cout<< " please enter a number ";
    int a;
    cin>> a;                                 //First user input
    cout << "please enter another number";
    int b;
    cin>> b;                                 //second user input

        return a + b ;
    }

    void writeAnswer(){                      // A function to output the final result
        cout<< "the sum of the two numbers is "<< readNumber() ;}

    ]

    (main.cpp) where the function "writeAnswer" was forward declared for question two
    [int main()
    {
       int writeAnswer();
    return 0;
    }
    ]

    (Question 3)io.h [#include<iostream>
    #ifndef io_h
    #define io_h

    using namespace std;

    int readNumber()
    {
        cout<< " please enter a number ";
    int a;
    cin>> a;                                 //First user input
    cout << "please enter another number";
    int b;
    cin>> b;                                 //second user input

        return a + b ;
    }

    void writeAnswer(){                      // A function to output the final result
        cout<< "the sum of the two numbers is "<< readNumber() ;}

    #endif // io_h
    ]

    main.cpp file which included the io.h as header file

    [#include <iostream>
    using namespace std;
    #include "io.h"
    int main()
    {
        writeAnswer();
    return 0;
    }
    ]

    • Alex

      In question 1, it’s weird to have a function named readnumber() read two numbers and return the sum. Either break this into multiple functions or rename your function to indicate what it actually does.
      In question 2/3, it’s weird to have writeanswer() call readnumber(). If you didn’t know what writeanswer() did, would you expect a function named writeanswer() to ask the user for input? Probably not. readnumber() should be called in main and passed to writeanswer(), which should only do the writing.

      You seem to understand the syntax of the language okay. Work on understanding the proper use of functions (a function should have one job) and use variable passing to achieve that.

  • Joseph

    So I have make this multi file project, it is suppose to have two file.
    main.cpp

    io.cpp

    I built and ran, which led to to errors numbering into lines > 500.
    I clicked one of those errors which subsequently led to a file named ostream
    which very much resembles iostream.

    • Alex

      The problem is this line:

      writeValue is a function that does not return a value (the return type is void), but you’re trying to send the return value of the function to std::cout.

      Even if this did work, you’d have a recursive function that would loop forever, as writeValue is calling itself.

      You probably intended this:

  • Thomas Keith

    Alex,

    I’m puzzled (again.)

    I got through questions 1 an 2 ok, but on question 3, even though my files look identical to yours (except for some remarks), whenever I try to compile main.cpp, io.cpp or io.h, I get an error complaining that readNumber is undefined, though it is clearly defined in io.cpp.  When I look at main.cpp, the first use of readNumber() is flagged and upon scroll-over, it says "identifier readNumber is undefined", but the second time I call it (to initialize y,) isn’t flagged and neither is writeAnswer (also defined in io.cpp.)  I currently can’t compile any of these files because "readNumber is undefined."  I can post my code if you like, but you’ll find it very familiar, I think.

    Thanks for the help.

    • Alex

      This one sounds tricky to diagnose.

      A few things to check:
      1) Make sure all 3 files are added to your project.
      2) Make sure main.cpp #includes io.h
      3) Make sure the capitalization is all correct (readNumber, not ReadNumber)

      If none of that helps, contact me from the contact form in the support section of the website and we’ll try and diagnose this one offline.

  • Thomas Keith

    You got it!  readnumber (not readNumber) in my header file was not helpful.  Compiled after correcting that.  I should have caught that.  After all, Visual Studio was telling me that my variable was not defined.  I won’t make that mistake again. <crosses fingers>
    Thanks again!

  • jason paulaskas

    // ConsoleApplication1.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    int add(int x, int y) {
        return x + y;
    }
    int main(){
        int x, y;
        cout << "put two numbers" << endl;
        cin >> x >> y;
        cout <<"the answer is  ="<<" "<< add(x, y) << endl;
        return 0;
            
    }
    //i made it in an other way ;is that a bad programming ?

    • Alex

      Nope, this is okay, outside of the use of the “using namespace std” declaration in the global scope. You should move that line inside of main().

  • Rahul

    The code for my last program gives me this error

    Undefined symbols for architecture x86_64:

    main.cpp

    io.cpp

    io.h

    • Rahul

      NVM I hadn’t included the io.cpp in io.h is it necessary to include even if the filenames are same?

      • Devashish

        No it’s not necessary. In fact we should avoid #including .CPP files whenever possible. I run your code in my 32 bit machine and everything goes fine. So, I couldn’t spot the problem out there. Alex may help. But I would like to give some advices:
        Make your writeAnswer() function return void because it is only printing out result and caller won’t expect any return value (int) from this. Remove Don’t #include iostream in your .h file. That’s redundant. Well, main function will also work without #including iostream but generallygenerally we should include this in main().

      • Alex

        You should never #include .cpp files. It’s bad form, and can easily lead to duplicate definitions in your program.

    • Alex

      Did you remember to add io.cpp to your project?

  • Josh

    My code compiled and runs properly, but for question 3 I was under the impression you did not want forward declarations at all, so my io.h includes the functions for readNumber() and writeAnswer() rather than a .cpp with them and forward declarations for them in main(). i.e., I have no forward declarations. Is it better to do the way you have for any reason? Or is including the functions in the header better? Or is one just better practice?

    • Alex

      As noted in lesson 1.9 -- Header files, you should generally avoid putting your function definitions inside header files (see that lesson for some comments about why). Header files are intended to be used to propagate declarations.

      I updated the quiz text slightly to be more clear about what I’m looking for in question 3.

  • itamar elbaz

    My writeAwnser function got out a bit different but it works great.

  • Nat

    I have copied and pasted your code exactly as it is just to check for the flawlessness of task 2 and 3. I have included both the header and the io.cpp in the source files.
    However the compiler keeps telling me that there is an error, "an identifier not found" for the both functions.
    What must I have done wrong?

    • Alex

      I can’t help you debug this without an exact error message. Can you paste in the full error message so we can see what identifier it’s complaining about?

      • Nat

        Thanks for reply! Does that provide more info on the errors?

        Error    1    error C3861: ‘readNumber’: identifier not found    c:\users\nat\documents\visual studio 2013\projects\main.cpp\main.cpp\main.cpp.cpp    6    1    Main.cpp
        Error    2    error C3861: ‘readNumber’: identifier not found    c:\users\nat\documents\visual studio 2013\projects\main.cpp\main.cpp\main.cpp.cpp    7    1    Main.cpp
        Error    3    error C3861: ‘writeAnswer’: identifier not found    c:\users\nat\documents\visual studio 2013\projects\main.cpp\main.cpp\main.cpp.cpp    8    1    Main.cpp
            4    IntelliSense: identifier "readNumber" is undefined    c:\Users\Nat\Documents\Visual Studio 2013\Projects\Main.cpp\Main.cpp\Main.cpp.cpp    6    10    Main.cpp
            5    IntelliSense: identifier "writeAnswer" is undefined    c:\Users\Nat\Documents\Visual Studio 2013\Projects\Main.cpp\Main.cpp\Main.cpp.cpp    8    2    Main.cpp

  • Austin

    Hi, having a problem. It seems as if when I save it code blocks, it never saves the project file. It saves other files, but there is no project or work space files. When I try to put in the .cpp files individually, it won’t let me change the properties of the files. So it says “undefined reference” to all my io.h defines. Or maybe it’s not define but when you put “void blahblah(int x)” at the beginning of code.

  • Nicholas

    This is a really good way to learn C++. I likethese tutorials man great work. I hope you get paid a lot for what you’ve done for this generation of programmers.

  • Arjen

    Hi,

    As a java developer, I really LOVE your tutorial and of course, besides of the different syntax, it’s quite ease to implement until now.. 😉

    I even wrote the solution on question 2 already in the first question.. and tried the one liner version to see if that worked, which it did! 🙂

    You explain it very well!

    Will continue on this one the coming days!

    Thanks & regards,
    Arjen

  • Olha meu resultado aí, em pleno 2015.

    #include <iostream>
    #include <cstdlib>

    //Declara uma função para fazer uma leitura
    int readNumber();

    //Declara uma função para mostrar o resultado
    int writeAnswer(int y);

    int main()
    {
        int n1 = readNumber();
        int n2 = readNumber();
        writeAnswer(n1 + n2);
        system("pause");
    }

    int writeAnswer(int y)
    {
        std::cout << "O resultado é: " << y << std::endl;
    }

    int readNumber()
    {
        std::cout << "Insira um número inteiro:";
        int x;
        std::cin >> x;
        return x;
    }

  • Nic

    Hi, I seem to have trouble with the code even though the syntax is correct(I think).
    main.cpp

    io.cpp

    Header.h

    I get the error:

    What does that mean?

  • Oeleo

    Hello,
    I want to help you with allowing AdBlock on your site, but when I go on the homepage and pause or disabling AdBlock "on this domain" I always don’t see adds. However, I see them when I put a shortcut on my desktop and in this case I see them. Any idea to solve that ?

  • X

    Hello, Alex. I have a question.
    In "Solution 1, line 11", what’s the meaning of ‘int x’ within ‘void writeNumber(int x)’?? I can not understand it, even if I use ‘int s’ to instead of ‘int x’, the code can be executed successfully…..

    • Alex

      int x is a function parameter. It tells the compiler that function writeNumber() takes one parameter of type integer, with name x. So when we call writeNumber(), we need to pass it an argument (e.g. writeNumber(5)), and this argument will be assigned to parameter x when the function starts.

      Please re-review the lesson on function arguments and parameters.

  • Brady

    I was able to answer all three problems.  But had a couple questions about ordering and efficiency.  In mine I put int x as the first line in readNumber().  I’m guessing doing this in larger programs could cause poor performance by using unnecessary RAM?  And so it is more efficient to do it your way where x is filled and destroyed as quickly as possible to when it is created?
    Also, in main() I tried two different ways that both worked.  I was wondering if one of the three (my two ways and your solution) is better than the other two and why?  Here’s what I did:

    I just commented out one to try the other.
    Thanks!

    • Alex

      The ordering of the lines doesn’t really matter in terms of efficiency. The “define a variable as close to its first use as possible” is to reduce complexity, not affect performance. In both cases, the variable is created at the start of the function and destroyed at the end.

  • Sharaf

    main.cpp

    io.h

    io.cpp

    i didn’t use header guard but it still got compiled so plzz explain point header guard here?

    • Alex

      It looks like you used a header guard in io.h, since you have #ifndef io.h. It’s also a little weird to have your main function in io.cpp instead of main.cpp.

      But to answer your question, header guards prevent a header file from being #included multiple times into a given file (to prevent problems with redeclarations). Since your io.h only gets #included once, the header guard isn’t technically needed (but it’s still good practice to include it, since for more complicated programs you’ll want the header guards).

  • Garrett

    Whew, got through chapter 0-1 in one night, its 12 PM.. really tired, found this guide SUPER helpful though! Thank you!!!

  • Grampa Grump

    Hello! I’m not sure if you are still looking through these, but I wanted some feedback regarding what I put in main()

    The readNumber and writeAnswer functions were the same, but I noticed that I did the last part differently than what I had seen in the solutions and comments. What I did worked correctly, at least it asked for two numbers and then added them correctly.

    int main()
    {
        writeAnswer(readNumber() + readNumber());
        return 0;
    }

    Should I have done it like you did in the example by creating two new variables in main and passing those into writeAnswer instead of just calling the input function twice and using the return in the middle of calling the write function? I’m not sure if the way I did it or the way you did it would be more efficient for larger programs

    Also, thank you very much for the tutorials, they are very helpful!

    • Alex

      The way you did it is fine. Personally, I prefer having functions that ask for user input in their own individual statements, rather than nested inside another function call. To me, it reads cleaner, and makes the order that things execute in a little more obvious.

  • Randall L

    Alex! Thank you so much! Finally someone who can teach C++ the way my brain wants to learn it! You have no idea how much this site means to me. Maybe you do. You state something in a paragraph, and my brain starts to think "well, what about this other possiblity?" You then proceed in the very next sentence to address the question I was just thinking about.  This whole process makes so much more sense than it ever has any other time I’ve tried to learn C++. Honestly, thank you so much!!

  • gowtham

    I don’t understand the use of header guards. I did this exercise without header guards and it compiled just fine. I know i’m missing the point but just can’t figure out what it is!

    • Randall L

      I’ll try to answer this to test my own understanding. 🙂

      Header guards won’t make a noticeable difference when you only have a single header file you’re including, but it should be done anyway because it’s part of establishing good habits while programming. If you were including multiple files, there’s a chance (and probably a pretty good one) you would include the same files over and over through inheritance. (myProgram.cpp includes myMath.h and myConstants.h, however myConstants.h includes myMath.h too - This leads to code bloat).

      • Alex

        Code bloat is actually the lesser problem we’re trying to solve.

        The bigger problem is the fact a given identifier can only be defined once. If you try to define it twice, then the compiler will give you an error.

        So consider the case where you have a definition (of any kind) in A.h. B.h #includes A.h. main.cpp #includes both A.h and B.h. Without header guards, you’ll get two copies of the definition in main.cpp (one from A.h, and one from B.h, which it got from A.h). That will cause a compile error.

  • gowtham

    Thank you for your response. So can we generalise the function of header guards as a method to prevent errors due to definition duplication (while compiling)?

  • Rhys

    My question 1 attempt so far, won’t compile. Where am I going wrong? (haven’t looked at the answer yet)

    • Rhys

      Sorry, it DOES compile, just doesn’t work

    • Nyap

      semantic error (line 21)
      edit: I’m not sure actually, you’ve confused me aswell xD

    • Alex

      Your compiler should tell you exactly what’s wrong. When I compiled this, I got:

      1>...\consoleapplication1.cpp(29): error C4700: uninitialized local variable 'X' used
      

      And there it is. You’re passing the value of X to a function without having given it a value first.

    • Rhys

      If I like declare X = 1 first in main(), it stays as 1 and doesn’t get updated when it gets passed to readNumber & back. Like here’s my most recent version:

      • Alex

        When you pass variable X to function readNumber(), parameter A in readNumber becomes a copy of X, which you then overwrite with the user’s input. So first off, you should not pass X to readNumber(). Instead, readNumber() should not take a parameter and instead should declare its own local variable.

        Second, you return the user’s input from readNumber(), but you’re not doing anything with it, so it’s being discarded. You should assign this back to X (or Y as appropriate).

  • Nyap

    I did it differently for exercise 1. Is this still correct?

    • Nyap

      nvm, writeAnswer is supposed to have only one parameter
      back to the drawing board then

      edit: done, finished the test. Looking forward to chapter 2 😀

    • Alex

      It’s not wrong. But there are a few things to watch out for here:
      1) Nesting function calls inside of other function calls can be confusing.
      2) C++ doesn’t indicate whether functions should evaluate their parameters left to right or right to left. In this case, it doesn’t matter because your left and right parameters are identical. However, if you had a readNumber1() and readNumber2(), they might execute in different orders on different machines.

      I think it’s clearer if you split out the two readNumber() calls into their own statements. That way you have explicit control over the ordering, and each statement is simpler.

  • John

    I’ve been using this site purely on the whim in the hope that I might be able to learn something new quite casually in my spare time. So far (just got to the end of chapter 1!) I’ve found the style incredibly accessible and easy to follow. I have zero background in programming or anything particularly "codey" outside of being reasonable in Excel!  I hope the remaining content matches what I’ve seen so far!

    Great stuff so far!

  • brent

    if your still reading these, I wanted to say thank you for the time and effort you put into this for me to have access to lessons of this type, and your work here, so far has been outstanding !!
    I’m very grateful you found the time to teach others, like myself.
    great work !
    thank you sir.
    peace hope love
    Doc

  • Jatin

    Hi Alex, for question 2 I used the following code
    io.cpp

    main.cpp

    but the compiler is showing me errors like
    Roughio.cpp|4|error: ‘cout’ is not a member of ‘std’|
    Roughio.cpp|4|error: ‘endl’ is not a member of ‘std’|
    When I #include in io.cpp it runs fine .Why it is happening

    • Alex

      io.cpp uses std::cout and std::cin, which are defined in header file iostream, so io.cpp needs to #include iostream. The fact that you’ve included it in main.cpp only allows the code in main to use that functionality, not other files.

  • Malavika

    Hello,
    This question isn’t exactly related to this quiz. Whenever I use the command "return 0;" outside of the main function, in an int function, I find that the program actually prints the number 0 on-screen before proceeding. But if I make the function a void or char one, this doesn’t happen.

    Is this supposed to happen? Or am I missing something?

    By the way, this is my first time commenting here, and I’m glad to see you’re still here responding to every comment 🙂

    • Alex

      Returning a value simply passes that value back to the caller of the function. The caller can print that value if they wish, but that’s not required. The simple act of returning a value does not print anything in and of itself.

  • [#include "stdafx.h"
    #include <iostream>
    int readnumber()
    {
        int x = 0;
        std::cout << "please enter a number" << std::endl;
        std::cin >> x;
        return x;
    }
    int writeanswer(int y )
    {
        std::cout << y << std::endl;
        return 0;

    }
    int main()
    {
        int y = 0;
        int input1 = readnumber();
        int input2 = readnumber();
        y = input1 + input2;
        std::cout << y << std::endl;
    }
    ]
    is this one correct like for 1st answer it is not matching I did not void anywhere because I basically did not understand its usage but is this correct
    Thanks a lot

    • Alex

      It produces the correct output, but writeanswer() should have a return type of void and no return statement, otherwise your code is a bit misleading.

  • Abhishek

    Hi Alex,
    I modified my code to answer the 3rd question without seeing the solution (i modified only the io.h file the rest is same as yours) and i came up with this:
          In io.h

    #ifndef READNUMBER_H
    #define READNUMBER_H

    int readNumber();

    #endif // READNUMBER_H

    #ifndef WRITEANSWER_H
    #define WRITEANSWER_H

    void writeAnswer(int x);

    #endif // WRITEANSWER_H

    I compiled it and it works fine. I wanted to know if this is the correct way to code or efficient way to code or i should follow as you have mentioned. Thanks.

    • Alex

      If these are both in io.h, then no, this is not the right way to do things. The header guards should include the entire contents of the header.

  • Aaron

    It’s great how much this bit of practice helps!!! Thanks for this quiz…it helps to condense everything in chapter one into 3 questions 😉

  • Lauren

    Hmm, so I’m a little confused about what I should put in a header file: is it better to put just the forward declarations in the header file or to define the functions in the header file? And why?

    I also have a second, unrelated question: for some reason when I make a io.h file (analogous to your solution) with

    including "io.h" in main, the compiler throws an error and tells me it can’t find writeAnswer

    When I keep the exact same files, and just change io.h to

    which is what CodeBlocks automatically fills in for the name of the header, it works. Any ideas why case 1 doesn’t work?

    Sorry if these were covered elsewhere and I somehow missed it. And thank you for these tutorials, they’re fantastic!

    • Alex

      You should generally only put declarations in a header file. If you put a definition in the header file, that definition will be propagated to every code file that includes that header, which can lead to duplicate definition problems.

      It sounds like somehow IO_H is getting #defined more than once, so the contents of your io.h header file aren’t being included in your main code file. I’m not sure where this would be happening though.

  • I have the same problem as Lauren. I have the exact same code used for solution 3 with 3 different files. Somehow the compiler (using Microsoft Visual Studio 2015) doesn’t find io.h when going through main.cpp.

    It throws undefined errors by the way.

  • Olvin Lizama

    I was getting a compilation error, something that I thought was weird is that the io.cpp file must include the iostream library, my code will not work if not done so,

    io.h

    io.cpp

    main.cpp

    That was not commented I think so in the chapter 1.8 — Programs with multiple files, but I think anyone with a little common sense can realize it.

    Thanks for this great Course!!

  • Sav

    Hello,

       I am using Visual Studio 2015, and i have included the io.h and the io.cpp in my main.cpp file but when i compile it it still throws the error of identifier not found for the readNumber and writeAnswer. I have copied the answer given letter for letter and it is still not working. What did I do wrong?

    io.h:

    io.cpp:

    main.cpp:

    And as I stated before the io.cpp and the io.h are added in their respective areas in the solution explorer. Any insight would be appreciated.

    (this may seem silly but how am i supposed to use the code tags? I typed them in at the beginning and end of the code exactly how they are written and it did not seem to work)
    Thanks

    • Alex

      I don’t see anything wrong with your code. Are you getting a compiler error or linker error? If linker error, maybe io.cpp isn’t getting compiled as part of your project.

      Try copying the readNumber() and writeAnswer() prototypes from io.h and put it at the top of main and see if that compiles. If so, then something is going on with io.h. Maybe your header guards are having a naming conflict with something else?

      You use the code brackets like this:

      [code]
      Your code here
      [/code]

  • Jared

    I know that this isn’t too important, but why does "std::cin >> x;" act as a endl at the end? What if I wanted to say "
    std::cout << ‘Print two Numbers: ‘;
    std::cin >> x;
    std::cout " and ";
    std::cout >> y;" I want it to print "Print two numbers: x and y" yet it prints "Print two numbers: x
    *endl* and y" Sorry for bad formatting in code 😛

    • Alex

      std::cin waits for you to hit enter before trying to extract a value to your variable. Hitting enter causes a newline.

      There are 3rd party libraries available that allow you to do input without require the user hit enter, such as the curses I/O library.

  • Vlad

    Hi I have a problem too.At second question,I wrote this code inside a project(note that there are only these files in that project):
    io.cpp
    #include<iostream>
    using namespace std;
    int readNumber()
    {
      cout<<"enter a number:"<<endl;
      int x;
      cin>>x;
      return x;

    }
    void writeAnswer(int x)
    {
      cout<<"the result is:"<<x;
    }
    main.cpp
    #include<iostream>
    using namespace std;
    int readNumber();
    void writeAnswer(int x);

    int main()
    {
        int a = readNumber();
        int b = readNumber();
        writeAnswer(a + b);
        return 0;
    }
    I keep getting multiple definition of ‘main’ error even if I have only one main function inside the project.Any tips on solving this problem?
    note:I apologize if I have any grammatical errors,English is not my native language

    • Alex

      Somehow your compiler is compiling two main() functions, which means you have a second main function either in main.cpp, io.cpp, or some other file that’s getting compiled into your project by accident. My bet is on the latter.

  • Mohammad

    thank you so much!

  • ppippi

    Hi Alex, can I not globally declare a variable in io.h to be used in io.cpp and main.cpp, instead of declaring it twice?

    This is what I have and it doesn’t compile. 🙁

    io.h:

    io.cpp:

    main.cpp:

    Thanks!

    • Alex

      Putting global variables in header files is a really bad practice. Don’t do it.

      In this case, both main.cpp and io.cpp will get a copy of variable addAnswer. By default, non-const global variables have something called external linkage (a concept we explain in chapter 4). The end-result of this is that when the linker goes to link main.o and io.o, it sees that both have a variable of the same name, and doesn’t know how to reconcile this.

      There are quite a few ways to fix this, but the best way is to not do anything like this in the first place. You really shouldn’t be using global variables at all in this case.

      • ppippi

        I understand it a lot better now, thanks. I just read the following sub-chapter and I see why it’s bad practice. Since I learned C first and my professor encouraged global initializations, I assumed it would be good practice here too. Thank you!

  • My dear c++ Teacher,
    Please comment following program regarding question 1:

    With regards and friendship.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter