I started learning c++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();
}
Following the suggestion, I did some research and got why 'using namespace lib' is bad practice.
For example: If I have two libs and they have the same method, it would generate a conflict. So it would be better to use foo::method and bar::method
I updated the code to this:
#include <iostream>
int x;
int sum = 0;
int i = 0;
int addTwoNumbers()
{
while(i<2)
{
std::cin >> x;
if(std::cin.fail())
{
std::cout << "Error! Invalid Input" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
}
else
{
sum += x;
i++;
}
}
return sum;
}
int main()
{
std::cout << "Enter two integers" << std::endl;
return sum = addTwoNumbers();
}