当"x"不是数字时如何避免输出零?

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

本文关键字:何避免 输出 数字      更新时间:2023-10-16

我正在制作一个数字'应用程序,该应用程序告诉它是否为正,负,零或不是数字。我只有"非数字"条件有问题。如果" x"不是数字,我该如何告诉计算机显示输入的字符?

#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;
}

由于某种原因,它将输出显示为零,而不是我写的。

和一个示例,因此您将知道如何使用try-catch做到这一点。您可以说用户输入的所有内容都是字符串,然后您可以尝试将其作为INT解析。但是,用户可能不会输入字符串,因此您需要尝试解析并捕获任何错误。如果发生错误,则用户没有输入一个数字,而是完全不同的。如果用户输入了该号码,那么您就可以去检查是正面的,负数还是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;
}

我只是想出了这一点。谢谢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;
}