当"x"不是数字时如何避免输出零?
How to avoid the output zero when "x" is not a number?
我正在制作一个数字'应用程序,该应用程序告诉它是否为正,负,零或不是数字。我只有"非数字"条件有问题。如果" 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;
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++避免重复声明的语法是什么
- 在没有太多条件句的情况下,我如何避免被零除
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 当"x"不是数字时如何避免输出零?
- std::字符串流,直接输出缓冲区/字符串结果访问,避免复制
- 避免输出为负零的最佳方法是什么
- 避免在输出到 CppUnit 时出现点
- 输出浮点数为三位或更多,以避免指数
- 在c++中调用(date-set)时避免系统()输出
- 如何在进行回溯时避免输出参数
- 是否有一种简单的方法可以用可互操作的代码在CLI中清理屏幕/保持输出窗口,避免conio.h和ncurses.h
- 有没有一种正统的方法可以避免编译器警告 C4309 - 带有二进制文件输出的"truncation of constant value"?
- 避免c++缓冲输出中的内存占用
- 避免在 gperf 输出文件中避免"警告:声明 UserSuppliedStruct 不声明任何内容"