Hello all, absolute beginner here. My program compiles and runs just fine but it's not doing what it's supposed to do (namely taking user input) and I can't figure out why. The console output suggests it's bypassing the addNumbers function altogether? Any help would be greatly appreciated. Code and console output follows.
#include <iostream>
usingnamespace std;
int addNumbers();
int main (){
int addNumbers(int x, int y, int answer);
return 0;
}
int addNumbers(int x, int y, int answer)
{
cout << "Enter your first number: " << endl;
cin >> x;
cout << "Enter your second number: " << endl;
cin >> y;
answer = x + y;
cout << "The sum of your two numbers is: " << answer << endl;
return answer;
}
Console output:
1 2
(program exited with code: 0)
Press return to continue
To start with line 10 is a prototype that is best above main. Next you have not defined "x" or "y" or given these variables a value before you could call the "addNumbers" function.
There is nor reason to send "answer" to the function. Just define it in the function because you will be returning its value when the function ends. The same is true for "x" and "y". they are only used in the function. Even when you return the answer back to main you do not make use of it there. Move the last "cout" statement in "addNumbers" to main and it will make more sense as you will see in the following code.
#include <iostream>
#include <limits>
//using namespace std; // Bestnot to use.
int addNumbers();int addNumbers();
int main()
{
int answer{};
answer = addNumbers();
// This pauses the program befor the return statement ends the program. Mostly to keep the window open.
// The next may or may not be needed. If you have to press enter to see the prompt the next line can be
// commented out.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires heder file <limits>.
std::cout << "\n\n Press Enter to continue";
std::cin.get();
return 0;
}
int addNumbers()
{
int x{}, y{}, answer{};
std::cout << "Enter your first number: " << std::endl;
std::cin >> x;
std::cout << "Enter your second number: " << std::endl;
std::cin >> y;
answer = x + y;
std::cout << "The sum of your two numbers is: " << answer << std::endl;
return answer; // Or you could use (return x + y;) and not need the variable "answer"
}
Notice where I put the opening brace { in main. It makes it easier to read. I also put some blank lines in the code to break it up and make it easier to read.