Seif Boukhatem
Seif Boukhatem

Reputation: 105

How to avoid the output zero when "x" is not a number?

I'm making a numbers' application that tells if it's positive, negative, nil or not a number. I only have a problem with the "not a number" condition. How can I tell the computer to show the inputted characters if "x" is not a number?

#include <std_lib_facilities.h>
using namespace std;
int main()
{
    int x;
    cout << "x= ";
    x;
    cin >> x;
    if (x > 0)
    {
        cout << x;
        cout << " is a positive number";
    }
    if (x == 0)
    {
        cout << x;
        cout << " is nil";
    }
    if (x < 0)
    {
        cout << "(";
        cout << x;
        cout << ")";
        cout << " is a negative number";
    }
    if (cin.good())
    {
    }
    else
    {
        x != 0;
        cout << "x";
        cout << " is not a number";
    }
    return 0;
}

For some reason it shows the output as a zero and not as I wrote it.

Upvotes: 2

Views: 85

Answers (2)

golobitch
golobitch

Reputation: 1334

And one example so you will know how to do this with try-catch. You can say that everything that user enters is a string, and then you can try and parse this as int. However, there is possibility that user will not enter string, so you need to try to parse and catch any error if it occurs. if error occurs, then user did not enter a number, but something completely different. If user entered the number, then you are good to go, to check if it is positive, negative or 0.

#include <iostream>

int main(int argc, const char * argv[]) {
    std::string x;
    std::cout << "Enter a number: " << std::endl;

    try {
        std::cin>>x;
        int number = std::stoi(x);
        if (number < 0) {
            std::cout << "Negative number" << std::endl;
        }
        else if (number > 0) {
            std::cout << "Positive number" << std::endl;
        } else {
            std::cout << "You entered number 0" << std::endl;
        }
    }catch(...) {
        std::cout << "Not a number!" << std::endl;
    }
    return 0;
}

Upvotes: 1

Seif Boukhatem
Seif Boukhatem

Reputation: 105

I just figured that out. Thanks Sandburg.

#include <std_lib_facilities.h>
using namespace std;

int main()
{
    int x;
    cout<<"x= ";x;
    cin>> x;
    if (cin.good()) 
    {
        if (x>0)
        {
            cout<< x;
            cout<<" is a positive number";
        }

        if (x==0)
        {
            cout<< x;
            cout<<" is nil";
        }

        if (x<0)
        {
            cout<<"(";
            cout<< x;
            cout<<")";
            cout<<" is a negative number";
        }
    } 
    else
    {
        cout<< "x";
        cout<< " is not a number";
    }

    return 0;
}

Upvotes: 1

Related Questions