Ints和Doubles的输入验证

Input Validation With Ints and Doubles

本文关键字:输入 验证 Doubles Ints      更新时间:2023-10-16

因此,我试图让用户在选择数组大小时只接收整数,但如果我输入浮点数,则这些数字不会相加。如果他们输入字母,就会弹出正确的错误消息,但如果他们按照我目前的方式输入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;