0

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();
}
EAzevedo
  • 751
  • 2
  • 17
  • 46
  • Just in passing: the input is **text**; the question should be "does the text represent a valid integer". I know that sounds a bit pedantic, but it's an important distinction that must not get lost. – Pete Becker Sep 07 '17 at 16:00
  • You mean that when I use cin and give an input, that is recognised by the program as a text? like: cin >> x '1' for example. – EAzevedo Sep 07 '17 at 16:04
  • 1
    With `std::cin >> x` you type text (hopefully, just number keys), and the stream extractor converts that text to an integer value if it can. – Pete Becker Sep 07 '17 at 17:46
  • Ok thanks for the explanation! – EAzevedo Sep 07 '17 at 18:21

0 Answers0