Ints和Doubles的输入验证
Input Validation With Ints and Doubles
因此,我试图让用户在选择数组大小时只接收整数,但如果我输入浮点数,则这些数字不会相加。如果他们输入字母,就会弹出正确的错误消息,但如果他们按照我目前的方式输入4.4、1.21等,我就无法正确输入。我这样做很难吗?我用字符串流会更好吗?我遗漏了一大块代码。
#include <iostream>
#include <limits>
int main()
{
const int CAPACITY = 100;
int choice;
int size = 0;
double array[CAPACITY];
do
{
std::cout << "Hey there! Pick an option" << std::endl;
std::cout << "Hit 1 to do some math " << std::endl;
std::cout << "Hit 2 to quit" << std::endl;
std::cin >> choice;
if (choice == 1)
{
std::cout << "Choose the size of your array. The array can be set to capacity of 100" << std::endl;
//std::cin >> size;
if((std::cin >> size).fail()) {
std::cin.clear();
std::cin.ignore(1000, 'n');
std::cout << "Invalid input" << std::endl;
continue;
}
if(size <= 0){
std::cout << "Sorry, that not a valid option" << std::endl;
continue;
}
if (size > CAPACITY){
std::cout << "Sorry, that is too large" << std::endl;
continue;
}
if (size < CAPACITY){
std::cout << "Add some numbers to your array" << std::endl;
for (int i=0; i < size; i++)
{
std::cout << "Enter a number: " << std::endl;
std::cin >> array[i];
}
正如您所提到的,std::stringstream在这种情况下是的解决方案
std::string s;
std::cin >> s;
std::stringstream ss(s);
int n;
// Only accept if stringstream is empty after parsing
if(! (ss >> n) || !ss.eof() )
std::cerr << "something's fishy with '" << s << "'" << std::endl;
相关文章:
- 正在尝试了解输入验证循环
- 如何在C++中检查2D数组中负值的输入验证
- cin 的十进制输入验证?
- 输入验证以筛选出字符、字符串和一系列整数
- 输入验证将数字放入向量中
- 在C++中使用字符数组进行输入验证
- 在C++中使用字符数组进行用户输入验证
- C++ 中字符数组的输入验证
- 检查节点的输入验证的整数
- 如何让我的程序在输入验证的基础上读取素数
- C++ 用户输入验证无法正常工作
- 程序终止,而不是继续整数输入验证循环
- 使用REGEX进行电子邮件输入验证C
- C++:输入验证器函数
- 将用户输入验证为整数:用户必须两次输入输入
- C 输入验证
- C :对输入验证函数进行编程的性能影响可以对其进行编程,而每次都可以将其编程
- 使用模板函数进行通用输入验证
- 为什么用于输入验证的 while 循环要么完全跳过循环,要么不考虑错误的输入
- 仅 C++ 字母和空格输入验证