当输入参数外的输入时,循环没有正确反应。它应该只接受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];
}
}
}
问题:
解决方案:
例:
#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 << ", ";
}
}