我正在编写一个代码,该代码从用户那里为公司中的五个项目输入数量

I'm writing a code that takes a quantity input from the user for five items in a company

本文关键字:代码 为公司 五个 输入 项目 那里 一个 用户      更新时间:2023-10-16

我的问题是当用户输入其中一个项目数量的十进制值时,程序会自动结束。另一方面,我需要它做的是显示一条消息,让用户知道他们犯了错误,并让他们选择重试。

我尝试使用cin.fail()函数没有任何运气。

 cout<< "nEnter number of Whizbangs: ";
 cin>> WhizbangsAmt;
 //This screens out all the negative numbers
 while(true)
 {
     if(WhizbangsAmt < 0)
     {
         cout<< "Number is negative!n";
         cout<< "Enter number of Whizbangs: ";
         cin>> WhizbangsAmt;
     }
     else
     {
         break;
     }
 }

您发布的代码难以理解。请考虑使用函数读取整数,而不是使用原始std::cin函数。通过使用unsigned int,您可以确定整数的第一个位,因此您可以选择代数符号。

unsigned int readInt(std::istream& stream) {
    /*
     * Function to get integers, that are entered by the user
     */
    unsigned int input;
    stream >> input;
    return input;            
}
相关文章: