-4

So when I created a program that takes 2 integers, add them together and write it to the console. The thing is that I'm learning to use multiple classes. The program works but after getting the first integer, the console pauses and only continues after I enter another integer. Can you guys hint/explain me what is going wrong?

int readNumber()
{
    cout << "Enter an integer: ";
    int x;
    cin >> x;
    return x;
}

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

int main()
{
    int x;
    readNumber();
    cin >> x;

    int y;
    readNumber();
    cin >> y;

    int result = x + y;

    writeAnswer(result);

    system("pause");
}

1 Answers1

4

Within this block of statements:

int x;
readNumber(); // first time
cin >> x; // second time

the std::cin object is called twice. That's why you are seeing the pause. Eliminate needless calls to std::cin and replace the above with:

int x = readNumber();

Do the same for the y variable.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
Ron
  • 14,674
  • 4
  • 34
  • 47
  • Thanks for the in depth explanation. Not gonna make this mistake a second time now! – Ivo van der Bruggen Feb 02 '18 at 12:32
  • Also, please have a look at this [C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) list. – Ron Feb 02 '18 at 12:32
  • Thanks. I was just looking for some books on C++. Any specific you recommend from that list? I do have programming experience so a barebones beginner book isn't what I'm looking for. – Ivo van der Bruggen Feb 02 '18 at 12:33
  • @IvovanderBruggen Only at market rates. Kidding. That part is up to you. – Ron Feb 02 '18 at 12:34