This tutorial will read in two numbers from the console line and output the answer of the two integer values.
The cin refers to the console input, the >> allows the console input value placed into the variable (in this case the val1, val2), NOTE. << would mean output. With using the exception, and the try catch block of code allows for any errors in the conversion of the input into a integer value. Within the printf, there are a few conversion types, the %d means using the corresponding parameter within printf and output a integer value, %s means a string. When I say the corresponding parameter, if there are two %d within the output string, it will display in order the values attached to the printf(...) call. The code
#include
#include
//using the namespace std (standard) for the cin -> console input
using namespace std;
int main()
{
// setup the defaul values.
int val1 =0, val2 =0;
try
{
// output to the console
printf(“Please enter number 1 : “);
// read in the input, if not a integer value, this will
// cause a error
cin >> val1;
printf(“Please enter number 2 : “);
cin >> val2;
}
catch (exception& e)
{
// write out any error exception
printf(“Not a valid input %s\n”, e.what());
}
// output the answer of the two inputted values.
printf(“Answer : %d\n”, (val1 + val2));
return 0;
}
save this as cppaddtwonumbers.cpp. Once compiled (g++ cppaddtwonumbers.cpp -o cppaddtwonumbers (the -o means to output to the filename else a a.out file name would be created))
Once executed the program, cppaddtwonumbers within Windows, or ./cppaddtwonumbers within Linux/Unix.
The output would be
Please enter number 1 : 23 Please enter number 2 : 41 Answer : 64