C++输入验证(时间)
C++ Input Validation (Time)
你好,我正在尝试为时间做一个输入验证if语句。用户将输入一个数字,如果它是一个涉及时间的无效数字(即负数或25小时),代码将显示"无效输入",并将您返回到上一个问题,以便您可以重新输入有效输入。这是我目前所掌握的,但似乎不起作用。
cout << "Please enter the current processing hour." << endl;
cin >> hr;
if (hr >= 0 && hr < 24)
cout << "Invalid Input, try again.";
cout << endl;
cout << "Please enter the current processing minute." << endl;
cin >> min;
if (min >= 0 && min < 60)
cout << "Invalid Input, try again.";
cout << endl;
cout << "Please enter the current processing second." << endl;
cin >> sec;
if (sec >= 0 && sec < 60)
cout << "Invalid Input, try again.";
cout << endl;
您的情况很糟糕:
我给你一个:
如果(hr>=0&&hr<24)
应该是
如果(hr<0||hr>23)
这是假设小时数可以从0到23。(正如Mike在下面建议的那样)
您需要一个循环,以便它可以返回并重试:
while(1) {
cout << "Please enter the current processing hour." << endl;
cin >> hr;
if (hr >= 0 && hr < 24)
break;
cout << "Invalid Input, try again.";
}
cout << endl;
您的代码没有循环。你的语句只是执行然后停止。您需要某种形式的循环,直到输入正确为止。
此外,您的if
语句也没有花括号。因此,如果条件为true,它总是只执行下一个语句,如果条件是false,则跳过该语句。如果将括号放在那里,通常会更容易维护代码。
这里有一个示例片段来说明什么可以为您工作
using std::cout;
using std::cin;
using std::endl;
int hr;
int isValid = 0;
while(0 == isValid)
{
cout << "Please enter the current processing hour." << endl;
cin.clear();
cin >> hr;
cout << "Input '"<< hr << "'" << endl;
if (hr >= 0 && hr < 24)
{
isValid = 1;
cout << "Valid." << endl;
}
else
{
cout << "Invalid, try again." << endl;
}
}
请注意,我是如何使用变量来跟踪输入状态,而不是通过break;
逃离循环的。这使得函数只能有一种退出方式。通常这是降低错误率的一件好事。
下面是更详细的代码:
#include <iostream>
int getAndValidateInteger(const char * question, int min, int max);
int main(int argc, char* argv[])
{
int hour, minutes, seconds;
hour = getAndValidateInteger("Please enter the current processing hour.", 0, 23);
minutes = getAndValidateInteger("Please enter the current processing minute.", 0, 59);
seconds = getAndValidateInteger("Please enter the current processing second.", 0, 59);
return 0;
}
int getAndValidateInteger(const char * question, int min, int max)
{
using std::cout;
using std::cin;
using std::endl;
int number;
int isValid = 0;
while(0 == isValid)
{
cout << question << " (Range [" << min << ";" << max << "])" << endl;
cin.clear();
cin >> number;
cout << "Input '"<< number << "' " ;
if (number >= min && number <= max)
{
isValid = 1;
cout << "is valid." << endl;
}
else
{
cout << "is invalid, try again." << endl;
}
}
return number;
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 从持续时间构造std::chrono::system_clock::time_point
- 正在尝试了解输入验证循环
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在已经使用Git的情况下减少编译时间
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 如何在C++中检查2D数组中负值的输入验证
- 从文本文件中读取时钟时间和事件时间并进行处理
- 具有未知值时的时间复杂性
- 如何减少花费的时间
- C++在变量给定的指定时间内关闭电脑
- 有没有办法关闭提升日期和时间验证
- 具有编译时间验证的ConstexPR构造函数
- 日期时间验证截止到2012年7月25日15:08:23
- 解析错误输入时的c++ boost时间验证
- C++输入验证(时间)