c++ - 尝试了解输入验证循环

标签 c++ validation input clion

在此while循环输入验证中,在调用我的控制台输出后将显示cerr。它显示为“输入费率:$无效费率”。
例如:

Enter rate: $750
Enter rate: $Invalid Rate. 

它与do-while循环相同。有什么建议或帮助吗?
#include <iostream>

using namespace std;
#define max_rate 50
#define max_hours 80

int main() {

   // input validation loop (loops until input is valid)
   double rate, hours;

   cout << "enter rate: $";
   cin >> rate;
   cin.ignore();

   while (rate > max_rate){
       if (rate > max_rate){
           cerr << "Invalid Rate." << endl;
       }
       cout << "enter rate: $";
       cin >> rate;
   }

   do {
       if (hours > max_hours) {
           cerr << "Invalid hours." << endl;
       }
       cout << "enter hours: ";
       cin >> hours;

       }
   while (hours > max_hours);


   double pay = rate * hours;
   cout << "$" << pay << endl;
   return 0;

最佳答案

答案是,首先阅读,然后检查,再声明第三。那是,

for (;;) { // the same as while(true)
    cin >> rate;
    if (rate is valid)
        break;
    cout << "Invalid rate\n";
}

并且不要无故混用coutcerrcout延迟输出,将数据存储在内部缓冲区中,而cerr立即打印。 (但cout会在使用cin时刷新缓冲区;还可以显式调用cout.flush [或cout << flush])。

关于c++ - 尝试了解输入验证循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60406754/

相关文章:

c++ - OpenGL 新手,正在处理 "paint"程序

forms - 如何在 angularjs 指令中添加验证属性

c# - 使用 HTML 编码字符的 ASP.NET 请求验证

java.util.NoSuchElementException - 扫描仪读取用户输入

c++ - 如何将返回类型声明为模板类型名的内部类?

c++ - 为什么 C++ 中的 shell 脚本代码不起作用?

javascript - 仅使用输入字段上传文件 - React Hook Form

Linux屏幕输入自动响应

c++ - 如何处理代码中的数据库凭据

validation - Magento,翻译验证错误信息