We started to learn c++ on the course, I am doing something very easy, add two number. The work does not require anything else. I wanted to just check if the input giving was an integer, I tried to search for an answer but did not get anywhere.
For example:
int x;
if(cin >> x) // < does it check if the input is the same type as the
// variable declaration?
But it just doesn't really work...
So I tried to do:
if(isdigit(x[i])) // I declared char x []; instead of int x;
and after tried to convert the x into int
sum += (int)x;
and my main function:
return sum = myFunction();
But after giving two inputs, the program return "Invalid Input". What is the result of isdigit(x[i]) returning false. But it happens even though I wrote two integers.
That is the complete code:
#include <iostream>
#include <ctype.h>;
using namespace std;
char x [] = "";
int sum = 0;
int i = 0;
int additionOfTwoNumbers()
{
while(i<2)
{
cin >> x;
if(isdigit(x[i]))
{
sum += (int)x;
i++;
}
else
{
cout << "Invalid Input";
}
}
return sum;
}
int main()
{
cout << "Enter two integers" << endl;
return sum = additionOfTwoNumbers();
}
Thanks.
Don't know if even with this question closed someone can find it.
So I wanna share what I got from the question that is marked on the top as containing the answer.
#include <iostream>
#include <ctype.h>;
using namespace std;
int x;
int sum = 0;
int i = 0;
int additionOfTwoNumbers()
{
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 = additionOfTwoNumbers();
}