Navigation



1.11 — Comprehensive quiz

1) Write a program that reads two numbers from the user, adds them together, and then outputs the answer. The program should use two functions: A function named ReadNumber() should be used to get an integer from the user, and a function named “WriteAnswer” should be used to output the answer. You do not need to write a function to do the adding.

2) Modify the program you wrote in #1 so that the function to read a number from the user and the function to output the answer are in a separate file called “io.cpp”. Use a forward declaration to access them from your main() function, which should live in “main.cpp”.

3) Modify the program you wrote in #2 so that it uses a header file to access the functions instead of forward declarations. Make sure your header file uses header guards.

Quiz solutions

1) Show Solution

2) Show Solution

3) Show Solution

2.1 — Basic addressing and variable declaration
Index
1.10a — How to design your first programs

165 comments to 1.11 — Comprehensive quiz

  • 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

     #include

    should be

    #include <iostream> 

    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.

    #include "stdafx.h"
    #include <iostream>
    
    int som(int x, int y)
    {
    	return x+y;
    }
    
    int main()
    {
    	using namespace std;
    	cout << "Enter a number: ";
    	int x;
    	cin >> x;
    	cout << "Enter another number: ";
    	int y;
    	cin >> y;
    	cout << "That adds up to: " << som(x,y) << endl;
    	return 0;
    }
    
    • 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.

      int main()
      {
          int x = ReadNumber();
          int y = ReadNumber();
          int z = ReadNumber();
          WriteAnswer(x+y+z);
          return 0;
      }
      
  • 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?

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

    • SkinnY
      #include "stdafx.h"
      #include <iostream>
      
      int som(int x, int y)
      {
      	return x+y;
      }
      
      int main()
      {
      	using namespace std;
      	cout << "Enter a number: ";
      	int x;
      	cin >> x;
      	cout << "Enter another number: ";
      	int y;
      	cin >> y;
      	cout << "That adds up to: " << som(x,y) << endl;
      	return 0;
      }
  • 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:

      int ReadNumber()
      {
          using namespace std;
          cout << "Input value please: " << endl;
          int x;
          cin >> x;
          return x;
      }

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

      void WriteAnswer(int x)
      {
          using namespace std;
          cout << "Your answer is: " << x << endl;
      }
  • 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 <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:\Users\Sanjay\Documents\Visual Studio 2008\Projects\jyo\cpp programming\quiz1.11b\Debug\quiz1.11b.exe : fatal error LNK1120: 2 unresolved externals
    1>Build log was saved at “file://c:\Users\Sanjay\Documents\Visual Studio 2008\Projects\jyo\cpp programming\quiz1.11b\quiz1.11b\Debug\BuildLog.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.

  • 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

    #include "IO1.h"
    
    int main()
    {
    	 int x = ReadNumber();
    	 int y = ReadNumber();
    	 WriteAnswer(x+y);
    	 return 0;
    }
    

    (2)IO1.cpp

    #include <iostream.h>
    int ReadNumber()
    {
    
    	 cout << "Enter a number: ";
    	 int x;
    	 cin >> x;
    	 return x;
    }
    
    void WriteAnswer(int x)
    {
    
    	 cout << "The answer is " << x << endl;
    }
    

    (3)IO1.h

    #ifndef IO1_H
    #define IO1_H
    
    int ReadNumber();
    void WriteAnswer(int x);
    
    #endif
    

    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.

  • 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 :[[

  • chris

    Can some body please help me.
    Why does this generate an answer of 2 ever single time (no matter what x,y are)

    #include

    using namespace std;

    int readNumber(int x, int y, int z)
    { cout <> x;
    cout <> y;

    return z=x+y;
    }

    void writeAnswer(int z)
    {cout << "The answer is : " << z;}

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

  • chris

    #include

    using namespace std;

    int readNumber(int x, int y, int z)
    { cout <> x;
    cout <> y;

    return z=x+y;
    }

    void writeAnswer(int z)
    {cout << "The answer is : " << z;}

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

  • deep

    hello i wrote this progam
    // io.cpp : Defines the entry point for the console application.
    //

    #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 << endl;
    }

    and

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

    #include "stdafx.h"
    #include

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

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

    bt they r showin an error to this
    like
    1>—— Build started: Project: main2, Configuration: Debug Win32 ——
    1>Linking…
    1>main2.obj : error LNK2019: unresolved external symbol “void __cdecl WriteAnswer(int)” (?WriteAnswer@@YAXH@Z) referenced in function _main
    1>main2.obj : error LNK2019: unresolved external symbol “int __cdecl ReadNumber(void)” (?ReadNumber@@YAHXZ) referenced in function _main
    1>C:\Documents and Settings\HCL\My Documents\Visual Studio 2008\Projects\main2\Debug\main2.exe : fatal error LNK1120: 2 unresolved externals
    1>Build log was saved at “file://c:\Documents and Settings\HCL\My Documents\Visual Studio 2008\Projects\main2\main2\Debug\BuildLog.htm”
    1>main2 – 3 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
    pl wt s da problem

  • 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? :)

  • 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 :(

  • 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

    
    #include <iostream>
    #include "io.h"
    // add takes two integers as parameters, and returns the result of their sum
    // add does not care what the exact values of x and y are
    
    int main()
    {
        using namespace std;
        int first = ReadNumber();
        int second = ReadNumber();
        WriteAnswer(second + first);
        cin.clear();
        cin.ignore(255, '\n');
        cin.get();
    
        return 0;   
    
    }
    

    io.cpp

    #include <iostream>
    int ReadNumber()
    {
        using namespace std;
        cout << "What's the number you want to add?";
        int number;
        cin >> number;
        return number;
        }
    void WriteAnswer(int number)
    {
         using namespace std;
         cout << "When added, the answer is: " << number  << endl;
    }
    

    and lastly, my header file, io.h:

    #ifndef IO_H  //IF Not DEFined, then do the following stuff
    #define IO_H  //DEFINE name
    #include "io.cpp"  //This is the line I can't live without :(
    //Definitions here
    int ReadNumber();
    void WriteAnswer(int number);
    
    #endif //finish up the ol' definition
    

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

  • Icarus

    i can’t compile your program even though i pasted it. in both #2 and #3 compiler complains that functions are not defined.

  • Y2kX

    Solution 3 won’t work for me unless I put

    #include “stdafx.h”
    #include

    before putting
    #include “io.h”

    how come?

  • King Bob

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

        int x = ReadNumber();
        int y = ReadNumber();

    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.

  • Biplav

    HI, So can someone give me other quizzes too because sucked at these.

  • seraphist

    So i copied the exact awnser given for quiz one into MS visual C++ 2010 and tried to run it and could not for the life of me get it to work. is there some obvious addition that had been left out of the awnser, due to perhaps how seemingly obvious its presence would be or is there some mistack i have not managed to find? and i did add in ” #include “stdafx.h” ” as my first line for obvious reasons.

  • 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();
    }

  • 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.

    • chachoblow

      I was thinking the same thing. Seems a lot simpler to just put it at the top and make it “global” as you said.

      Also what is wrong with just writing:

      #include “stdafx.h”
      #include

      using namespace std ;

      int main ()
      {
      int x;
      int y;
      cout <> x >> y ;
      cout << "The answer is: " << x + y << endl;

      return 0 ;
      }

      Simpler is better imo

      • chachoblow

        *oops copied wrong

        #include “stdafx.h”
        #include

        using namespace std ;

        int main ()
        {
        int x;
        int y;
        cout <> x >> y ;
        cout << "The answer is: " << x + y << endl;

        return 0 ;
        }

  • chachoblow

    idk why but when i submit comment it switches the code all around :/ so i guess nvm

  • eturnallife

    chachoblow
    to write it like that is to go around what alex is trying to convey, how to use the linker for header files and declarations. it is good to see you are in the mind set of thinking ahead and outside of the box this early in the tutorial. Bravo sir!!

  • 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:

  • HelloCoder

    hey guys!
    i’m in kind of a fix and was wondering if you could help me out. For the first question i made the code accordingly and fixed all the debug errors, but this error won’t go away! Here’s my code. Please post back soon…
    #include
    #include
    int ReadNumber()
    {
    using namespace std;
    cout << "To find the addition of two numbers please think of two numbers." << endl <<"Now enter the first number" <> x
    cout << endl;
    cout << "Good, now enter the second number" <> y ;
    cout << endl
    return x,y;
    }
    int WriteNumber(int x, int y)
    {
    using namespace std;
    cout << "The sum of your two numbers is " << x+y << endl;
    return 0;
    }
    int main()
    {
    using namespace std;
    ReadNumber();
    WriteNumber();

    return 0;
    }

    ERRORS

    in function 'int ReadNumber' o few arguments to function 'int WriteNumber (int, int)'
    error: at this point in the file
    error :t

    • zingmars

      2x #include? what exactly did you include?
      ReadNumber() does not have any numbers defined (should be ReadNumber(int x, int y)).
      Also you need to use Cin >> x (or y) to take input. Even if your compiler supports such monstrosities, you’re not supposed to do it like that.
      Also you can simply add << endl the end of the cout.
      Missing semicolons.
      You should've used void WriteNumber(int x, int y), because it's not supposed to return any value.
      You should re-read all the tutorials before, because it will require a lot of rewriting to get it to working state.

    • zingmars

      Ah, never mind. I didn’t notice that this comment box somehow destroys your code formatting for some reason. Either way, I would guess that the problem came from the fact that WriteNumber wasn’t void, and that you didn’t do the whole WriteNumber(int x, int y) thing.

  • 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

  • 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.

  • Nurver

    Hey! Great Tutorial man!

    I was attempting the second problem but i cannot figure out this error.

    the code and the error are:

    io.cpp

    #include

    using namespace std;
    int a=0,b=0;

    int Readnumber()
    {
    cout<>a;
    cout<>b;
    return a+b;
    }

    void Writeanswer()
    {
    cout<<"the answer is "<<Readnumber();

    }

    main.cpp

    int Readnumber();

    void Writeanswer();

    int main()
    {
    Writeanswer(); // error HERE!
    return 0;
    }

    error obj\Debug\main.o||In function `main':|
    C:\Program Files\CodeBlocks\Quiz1.2\main.cpp|9|undefined reference to `Writeanswer()'|
    ||=== Build finished: 1 errors, 0 warnings ===|

    Please help me out. Seems trivial i know. :/

    • Nurver

      Ok! I got it. So I didnot select Debug and release while creating the new file (in code blocks). That was the problem.
      Can Anyone tell me why that is important??

    • xero

      i believe the problem lies at void WriteAnswer()
      as far as my understanding goes you need to declare a variable, which can hold return value from ReadNumbers() function.
      segment of my code was as follows:
      void WriteAnswer()
      int z = ReadNumbers()
      cout << "Sum of both numbers is " << z << endl;
      and my main was just like yours.
      Someone please correct me if i am wrong.

  • 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

  • Kamakasy64

    hello everyone i am having a problem with the third exercise, well the problem is with the header blocker i am using code blocks as ide in Ubuntu here is the problem.

    io.h

    #unfdef IO_H
    #define IO_H

    int Readnumber();
    void Writeanswer(int x);

    #endif

    this the error i get when i compile it

    error:invalid preprocessing directive #infdef
    error:#endif without #if

    i dont put the other parts because i know they are right, but if you want i can post it.

  • quack

    Hey Kamakasy, I think you have a typo. Change “unfdef” to “ifndef”.

  • Hex

    #include “stdafx.h”
    #include

    int Number1;
    int Number2;
    int Operation;
    int Result;

    int Getnumbers()
    {
    using namespace std;
    cout <> Number1;
    cout <> Number2;
    return (0);
    }
    int Getoperation()
    {
    using namespace std;
    cout <> Operation;
    return (Operation);
    }
    int Calculate(int, char, int)
    {
    if (Operation = ‘+’)
    return Number1+Number2;

    if (Operation = ‘-’)
    return Number1-Number2;

    if (Operation = ‘*’)
    return Number1*Number2;

    if (Operation = ‘/’)
    return Number1/Number2;

    return (0);
    }
    void Printresult(int)
    {
    using namespace std;
    cout << "Your Result Is " << Result << endl;
    }

    int main()
    {
    Getnumbers();
    Getoperation();
    Result = Calculate(Number1, Operation, Number2);
    Printresult(Result);

    }
    this is my calculator code but it will only add the two numbers instead of any thing else. Help im a N00B.

  • Hex

    #include “stdafx.h”
    #include

    int Number1;
    int Number2;
    int Operation;
    int Result;

    int Getnumbers()
    {
    using namespace std;
    cout <> Number1;
    cout <> Number2;
    return (0);
    }
    int Getoperation()
    {
    using namespace std;
    cout <> Operation;
    return (Operation);
    }
    int Calculate(int, char, int)
    {
    if (Operation = ‘+’)
    return Number1+Number2;

    if (Operation = ‘-’)
    return Number1-Number2;

    if (Operation = ‘*’)
    return Number1*Number2;

    if (Operation = ‘/’)
    return Number1/Number2;

    return (0);
    }
    void Printresult(int)
    {
    using namespace std;
    cout << "Your Result Is " << Result << endl;
    }

    int main()
    {
    Getnumbers();
    Getoperation();
    Result = Calculate(Number1, Operation, Number2);
    Printresult(Result);

    }
    sorry this is the real code my computer failed

  • Vastor

    And… this is my trial… :D

    File : main.cpp

    #include
    #include “nUser_input.h”
    #include “nSum.h”

    using namespace std;

    int main()
    {
    int nResult;
    int y;
    nResult = WriteAnswer(y);
    cout << "Sums of the two number: " << nResult << endl;
    return 0;
    }

    File : nSum.h

    #ifndef NSUM_H_INCLUDED
    #define NSUM_H_INCLUDED

    int WriteAnswer(int x)
    {
    int nInput_1 = Read_Number();
    int nInput_2 = Read_Number();
    return nInput_1 + nInput_2;
    }

    #endif // NSUM_H_INCLUDED

    File : nUser_input.h

    #ifndef NUSER_INPUT_H_INCLUDED
    #define NUSER_INPUT_H_INCLUDED

    #include

    using namespace std;

    int Read_Number()
    {
    cout <> nInput;
    return nInput;
    }

    #endif // NUSER_INPUT_H_INCLUDED

    really wonder what to do when the instruction tell can’t use function to sum up the number input, so i just use return x + y ‘trick’…. xD

  • lelouche_z

    haha.. grabeh wla akong idea panu ko siya gagawin..
    XD

    more practice needed.. :D

  • xero

    First of all I would like to thank you a lot for providing such a holistic and easy to understand material on C++. Its really fun learning with you. Thank you again.
    After having gone through Quiz 1, I have following queries:
    1. int WriteAnswer() can be used instead of void WriteAnswer(), code works perfectly alright with this. Whats really the difference between both.
    2. Will there be detailed section on different/preferential ways on piping input/output results between/among function?
    3. Following is my code on Q1 Quiz 1 (I was only able to get my code running only after going through the solution). I would appreciate few comments.

    #include //Quiz 1 my solution after consulting answer from learncpp(dot)com

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

    void WriteAnswer()
    {
    using namespace std;
    int z = ReadNumber();
    cout << "Sum of Both Numbers is " << z << endl;
    }

    int main()
    {
    WriteAnswer();
    return 0;
    }

    • xero

      Another thing, you said in some section that using cout in some function with void return type would create a compiler error, however we see void WriteAnswer() working fine, how?

You must be logged in to post a comment.