为什么循环卡住了

why is loop stuck

本文关键字:循环 为什么      更新时间:2023-10-16

现在唯一剩下的问题是我的choice while 循环是无限的,因为 break 语句似乎根本没有脱离循环,所以程序不会读取answer循环。 此外,"无效条目"显示所有其他不正确的输入,而不是每次输入无效字符时都显示

#include <iostream>
#include <cctype>
using namespace std;
int getAges(int age, const int SIZE);
char getChoice();
void displayInOrder(int numbers[], const int SIZE, char choice);
void displayInReverse(int numbers[], const int SIZE, char choice);
int main()
{
const int SIZE = 5;
int numbers[SIZE] = { 1, 2 ,3 ,4, 5 };
char answer = 0;
int age = 0;
char choice = 0;
while (choice = getChoice())
{
    if (toupper(choice) == 'O')
    {
        displayInOrder(numbers, SIZE, choice);
        break;
    }
    else if (toupper(choice) == 'R')
    {
        displayInReverse(numbers, SIZE, choice);
        break;
    }
    else
    {
        cout << "Invalid entry! - Must be O or Rnn";
        break;
    }
}
while (toupper(answer) == 'Y')
{
    system("cls");
    age = getAges(age, SIZE);
    choice = getChoice();
    displayInOrder(numbers, SIZE, choice);
    displayInReverse(numbers, SIZE, choice);
    cout << "Run program again (Y or N)?  ";
    cin >> answer;
  if (toupper(answer) == 'N')
    {
        exit();
    }
}
return 0;
}
int getAges(int age, const int SIZE)
{
cout << "Enter " << SIZE << " ages: nn";
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
cin >> age;
cout << endl;
return age;
}
char getChoice()
{
char choice;
cout << "How do you want to see the ages displayed? nn Enter O for In Order, or R for In Reverse.nn";
cin >> choice;
return choice;
}
void displayInOrder(int numbers[], const int SIZE, char answer)
{
    cout << "Here are the ages in order: nn";
    for (int i = 0; i < SIZE; i++)
    {
        cout << numbers[i] << endl;
    }
}
void displayInReverse(int numbers[], const int SIZE, char answer)
{
    cout << "Here are the ages in reverse order: nn";
    for (int i = SIZE - 1; i >= 0; i--)
    {
        cout << numbers[i] << endl;
    }
}

1."无效条目"显示所有其他不正确的输入:你在while循环中有一个getChoice((调用,在这里:

else
{
    cout << "Invalid entry! - Must be O or Rnn";
    choice = getChoice();
}

后跟 getChoice(( 调用

while (choice = getChoice())

因此,不会处理前面的 getChoice((。

2.">如果用户输入N进行回答,我不确定如何关闭程序",您应该考虑是否可以到达第二个while循环以及在哪里设置answer变量或基本上在哪里接受用户输入以结束程序?你应该看看它是否可以在第一个while循环中得到照顾?