I am taking a c++ tutorial on learncpp.com and was asked to write a program that reads two numbers from the user and adds them together using one function to get the input and one function to print the answer and doing the rest in main(). What I started with was different from their solution, but I thought it would work. It printed 2130567168. I've now literally copy pasted their solution into my ide and it still prints that number. And yes I remembered to rebuild before running again.
#include <iostream>
int ReadNumber()
{
usingnamespace std;
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void WriteAnswer(int x)
{
usingnamespace std;
cout << "The answer is " << x << endl;
}
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
Second: delete line 13 EDIT: originally had 14 here instead
Third: I'm not sure what's causing the issue... usually 21blahblah implies an uninitialized number being outputted. Try fixing the 2 things I mentioned, see if anything different happens. Your program looks right...
Pointing out that moving using namespace std; to the global scope would be optimal in this case makes no sense?
Optimal in that fewer characters would be typed or optimal in that everything in the std:: namespace would be exposed in a larger scope? The former is a poor measuring stick. The latter is not exactly what I would call optimal.
So no, it makes no sense.
sargon94 wrote:
Second: delete line 14
It makes no sense to delete the line which does the output.
sargon94 wrote:
Third: I'm not sure what's causing the issue... usually 21blahblah implies an uninitialized number being outputted. Try fixing the 2 things I mentioned, see if anything different happens.
Random changes to a program in the hopes they change the outcome do not make sense, no. Unless you subscribe to the monkeys-with-typewriters school of debugging.