c++ - 输入字母、符号和负数时验证年龄输入以提示消息
问题描述
我想用我在下面写的代码来验证输入年龄
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 开始使用和索引是不好的模式
推荐阅读
- oracle - CURRVAL 和 NEXTVAL 默认值如何在 Oracle 11 中生成“ORA-0094: column not allowed here”
- typescript - 如何使用 TypeScript 重用类构造函数参数作为文字字符串?
- python - 基本 Python 练习:给定一个整数列表,如果有重复,则放置一个“*”
- javascript - 循环遍历单个元素 - Laravel
- python-3.x - Keras中的卷积自动编码器解码器错误
- java - 为什么这个函数调用中有 NullPointerException?
- pandas - 如何在 csv 文件中添加分隔符
- go - 我使用 goroutine 进行 parral 的内存激增,最终 oom
- android - Android LiveData 以陈旧的发射触发。. . 只有某些时候 。. . 房间数据库更新后
- python-3.x - 如何使用 ezdxf 返回“MTEXT”中的字符串?