为什么循环卡住

时间:2017-11-14 22:11:19

标签: c++ arrays function

现在只剩下问题了我的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 R\n\n";
        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: \n\n";
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? \n\n Enter O for In Order, or R for In Reverse.\n\n";
cin >> choice;

return choice;

}

void displayInOrder(int numbers[], const int SIZE, char answer)
{
    cout << "Here are the ages in order: \n\n";
    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: \n\n";
    for (int i = SIZE - 1; i >= 0; i--)
    {
        cout << numbers[i] << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

之后是

中的getChoice()调用
while (choice = getChoice())

因此不处理先前的getChoice()。

2。&#34; 我不确定如果用户输入N作为答案&#34;如何关闭程序,你应该考虑一下你是否能够达到第二个while循环,你在哪里设置answer变量,或者基本上是你在用户输入结束程序的地方?您应该看看它是否可以在第一个while循环中处理?