如何解决输入字母、符号和负数时验证年龄输入以提示消息
我想用我在下面写的代码验证输入年龄
cout << "Enter the Age of The " << qty << " Passenger(s) :: ";
for (int i = 1; i <= qty; i++) {
cout << "\nAge for Passenger " << i << " :: ";
cin >> age[i];
while ((!(cin >> age[i])) || (age[i]<=0)) {
// Explain the error
cout << "Error: Enter a valid age for Passenger " << i << " : ";
// Clear the prevIoUs input
cin.clear();
// discard prevIoUs input
cin.ignore(123,'\n');
}
}
但是,有一个问题。当我输入范围内的年龄时,程序将停止运行。 所以,我想问一下有没有什么有效的方法来验证年龄输入。
解决方法
考虑使用 std::getline
和 std::stringsstream
。所以你只是在阅读一行然后尝试解析它。
例如:
#include <iostream>
#include <sstream>
int main(int argc,const char * argv[])
{
int qty = 10;
int* age = new int[11];
std::cout << "Enter the Age of The " << qty << " Passenger(s) :: ";
for (int i = 1; i <= qty; i++) {
std::cout << "\nAge for Passenger " << i << " :: ";
std::string s;
std::getline(std::cin,s);
std::stringstream stream(s);
while ((!(stream >> age[i])) || (age[i]<=0)) {
// Explain the error
std::cout << "Error: Enter a valid age for Passenger " << i << " : ";
std::getline(std::cin,s);
stream = std::stringstream (s);
}
}
for (int i = 1; i <= qty; i++) {
std::cout << age[i];
}
delete [] age;
return 0;
}
另请注意,使用 using namespace std
和索引从 1 是不好的模式
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。