Skip to main content
1 of 3
EAzevedo
  • 239
  • 3
  • 10

Simple C++ program to add two integers

I started learning c++ and the first exercise was to create a small program to add two numbers. No more requirements. I did this and put a small validate the user input. I am sure that it could be much better written, so I appreciate all the critics and suggestions.

#include <iostream>
using namespace std;

int x; 
int sum = 0;
int i = 0;

int addTwoNumbers()
{
    while(i<2)
    {
        cin >> x;
        if(cin.fail())
        {
           cout << "Error! Invalid Input" << endl;
           cin.clear();
           cin.ignore(256,'\n');
        }
        else{
             sum += x;
             i++;
        }
   }
return sum;
}
int main()
{
    cout << "Enter two integers" << endl;
    return sum = addTwoNumbers();
}
EAzevedo
  • 239
  • 3
  • 10