尝试了解输入验证循环 [英] Trying to learn about input validation loops

查看:111
本文介绍了尝试了解输入验证循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In this input validation while loop, cerr is being displayed after my console output is called. It displays as "Enter rate: $Invalid Rate." For example:

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

它与do-while循环的作用相同。有任何建议或帮助吗?

It does the same with the do-while loop. Any advice or help?

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


推荐答案

答案是,先阅读,然后检查,再声明第三。也就是说,

The answer is, read first, check second, claim third. That is,

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

不要混用 cout cerr 没有理由。 cout 延迟输出,将数据存储在内部缓冲区中,而 cerr 立即打印。 (但 cout 会在使用 cin 时刷新缓冲区;也可以调用 cout。刷新 [或 cout<<刷新]。)

And don’t mix cout and cerr without a reason. cout delays output, accumulating data in an internal buffer, while cerr prints immediately. (but cout flushes the buffer on cin use; it is also possible to call cout.flush [or cout << flush] explicitly).

这篇关于尝试了解输入验证循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆