input numbers to int c++
Here is an example of how to input numbers in C++:
include
using namespace std;
int main() { int num1, num2, sum;
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
sum = num1 + num2;
cout << "The sum of " << num1 << " and " << num2 << " is " << sum << endl;
return 0;
}
Explanation:
1. We include the <iostream>
library to gain access to the input/output stream objects such as cin
and cout
.
2. The using namespace std;
statement allows us to use objects and functions from the std
namespace directly, without having to specify the namespace each time.
3. We declare three integer variables: num1
, num2
, and sum
.
4. The cout
statement is used to display the message "Enter the first number: " to prompt the user for input.
5. The cin
statement is used to read the value entered by the user into the num1
variable.
6. Similarly, the cout
and cin
statements are used to prompt the user for the second number and read it into the num2
variable.
7. We calculate the sum of num1
and num2
and store it in the sum
variable.
8. Finally, we use the cout
statement to display the sum to the user.
Note: The <<
operator is used to concatenate the strings and variables in the cout
statements. The >>
operator is used to extract input from the user and store it in a variable.