为什么输入验证的while循环要么完全跳过循环,要么不考虑错误的输入?

问题描述 投票:-1回答:1

当输入参数外的输入时,循环没有正确反应。它应该只接受0-9,但我可以将任何数字置为正或负,并按原样输出。

我已经尝试将int count设置为null并且在第4行设置为0,认为null可能允许while循环最初表示'while count <0或count> 9'。即使在null,它也完全跳过了整个循环,并且不允许任何输入。我这样设置它认为它会循环,因为count设置为0,但它似乎跳过里面的条件。这是一个较大的彩票计划内的一个小功能。

    void human(int user[], int size) {
        const int SIZEOF = 5;
        cout << "Enter your 5 lottery number picks.\n";
        int count = 0;
        while (count == 0) {
            if (count >= 0 and count <= 9)
                for (count = 0; count < SIZEOF; count++)
                {
                    cout << "Number " << (count + 1) << ": ";
                    cin >> user[count];
                }
            else 
            {
                cout << "You must enter 0-9: ";
                cin >> user[count];
            }       
        }
    }

//EDIT: Here is the code I used based on it being pointed out I was using the //counter

void human(int user[], int size) {
    const int SIZEOF = 5;
    cout << "Enter your 5 lottery number picks.\n";
        for (int count = 0; count < SIZEOF; count++)
        {
            cout << "Number " << (count + 1) << ": ";
            cin >> user[count];
            while (user[count] < 0 || user[count] > 9)
            {
                cout << "You must enter a number between 0 and 9: ";
                cin >> user[count];
            }
        }
}
c++
1个回答
0
投票

问题:

  • 您的函数缺少输出/返回值
  • 你的外环毫无意义
  • 你检查计数而不是输入
  • 你读入(可能)越界数组

解决方案:

  • 使用std :: vector代替数组
  • 考虑你的功能的输入和输出
  • 修复输入和循环

例:

#include <iostream>
#include <string>
#include <vector>

std::vector<int> lotteryInput(uint32_t count)
{
    std::vector<int> numbersPicked;
    std::cout << "Enter your " << count << "lottery number picks.\n";

    while(numbersPicked.size() < count)
    {
        int pick;
        std::cout << "Number " << numbersPicked.size()+1 << ": ";
        std::cin >> pick;
        if ((pick >= 0) && (pick <= 9))
        {
            numbersPicked.push_back(pick);
        }
        else
        {
            std::cout << "You must enter 0-9: \n";
        }
    }

    return numbersPicked;
}


int main()
{
    auto numbersChosen = lotteryInput(5);
    std::cout << "picked numbers: ";
    for(const auto& num : numbersChosen)
    {
         std::cout << num << ", ";
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.