-
Need help!
Salut! i am a newbie in c++ programming and as a beginner i am in trouble..:) i wrote a simple program in c++ for adding 2 numbers:
Code:
#include <iostream>
int main()
{
int n1, n2, sum;
sum = n1 + n2;
cout << "Give the first number:" << endl;
cin >> n1;
cout << "Give the second number:" << endl;
cin >> n2;
cout << "The result is...:" sum;
return 0;
}
what's wrong with that code..? i am using Dev C++ v4 compiler.when i debug it, it show me no errors but when i execute it, first ask me for the 2 numbers and then terminated without the result..any help??
-
you sum n1 and n2 before you get the data from the cin.
initialize the variables otherwise they contain random garbage
-
You may need to flush othe ostream buffer try.
cout << "The result is...:" << sum << endl;
and like he said do the calculation after you get the numbers.
-
cout, cin, and endl are in the std namespace, and you haven't specified that they are. There are two ways to do this. The first way is to specify it manually with the scope resolution operator( :: ) like so:
Code:
std::cout <<"whatever" <<std::endl;
The second(and usually preferred) method is to use the entire std namespace with a using statement:
Code:
#include <iostream>
using namespace std;
int main( )
{
cout <<"whatever" <<endl;
}
The using statement prevents you from having to put std:: in front of the objects
-
Code:
#include <iostream>
using namespace std;
int main()
{
int n1, n2, sum;
cout << "Give the first number:" << endl;
cin >> n1;
cout << "Give the second number:" << endl;
cin >> n2;
sum = n1 + n2;
cout << "The result is...:" << sum << endl;
return 0;
}
The namespace issue has been explained. The reason why you need to do sum= n1 +n2 after the values have been read from the user is, that C or C++ are no logical languages. sum= n1 +n2 is not a definition but a command that is only performed once with the result saved to sum. So you have to do things in the right order.
You also forgot a "<<" operator between "The result is...:" and sum.
-
Thanks for the help guys..but when i am trying to run the program, it terminates without giving the result..? only asks for the 2 numbers...
i am using Dev-C++ compiler v5
-
That's because after the result is printed the program exits and the console is closed. If you have the header conio.h (non-standard header) you could put getch(); at the end to wait for a key to be pressed, or maybe use std::cin with a dummy variable again.
-