0

So for a short introduction, im learning c++ and my question is kinda basic, i have been given a simple c++ question to check wether an integer is a positive, negative or zero but there is a fourth condition and its an error or unknown value just in case symbols or characters have been used in the input

#include <iostream>
using namespace std;

int main()
{
    int num;

    cout << "Enter an integer: " << '\n';
    cin >> num;
    if (num > 0)
        cout << "The number is positive" << '\n';
    else if (num < 0)
        cout << "The number is negative" << '\n';
    else if (num == 0)
        cout << "Zero" << '\n';
    else
        cout << "Error" << '\n';
    return 0;
}

As you can see above, everything works fine but until one thing that while when i used a character or any other symbol it reads it as a zero

i know its kinda silly question but i spent hours and nothing worked out, i tried removing the num==0 statement and it worked fine but i also wanted that 0 statement too, any help provided would be appreciated

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
KOBRA-
  • 1
  • `if(!(cin >> num)) { /* input didn't work! */ }` You can (and should) always check whether `cin >>` succeeded this way. – user17732522 Jan 22 '23 at 12:09
  • You should check the state of `cin` to see if a number was successfully read (note though this will only check that the input starts with a number, it won't check the whole line is valid) – Alan Birtles Jan 22 '23 at 12:10
  • Checking the status of `cin >> num` will not work correctly if your input is something like "42xyz". In this case, you'll read the 42 leaving "xyz" for later and there will be no error. I think you'll need to read a string and parse it. How exactly you'll do that (just `cin >> word` or with `getline`) depends on whether your input may contain whitespace. – nickie Jan 22 '23 at 12:12
  • Input to a std::string and use [std::stoi](https://en.cppreference.com/w/cpp/string/basic_string/stol) to convert to a number, the link even shows an example. If that function throws an exception the input was not a valid integer number. And I advice you to look around cppreference a bit more (containers and algorithms too) since it is an invaluable resource for anything C++ and its standard library. – Pepijn Kramer Jan 22 '23 at 12:14
  • Side note you really should **stop using** : `using namespace std;` – Pepijn Kramer Jan 22 '23 at 12:16

0 Answers0