![](/img/trans.png)
[英]How do I get my checkLength function to loop until the user enters in a password of more than 5 characters?
[英]How do I loop my program to continuously ask for a letter until the user enters a Q to end the program
完成后我意識到我需要循環它直到他們輸入 q,但我不知道該怎么做。 我正在尋找的是在選擇最后一個選項('q' 或 'Q')之前,主程序回到開頭,要求用戶插入一個字母。
#include <ctime> // For time()
#include <cstdlib> // For srand() and rand()
#include <iostream>
using namespace std;
int main()
{
int array[5];
int i, num, x;
char c;
float average = 0;
srand(time(0)); //This makes the set of numbers differnet every time
for (i = 1; i <= 5; i++)
{
array[i] = (rand() % 5) + 15;
}
cout << "Array elements are: \n";
for (i = 1; i <= 5; i++)
{
cout << array[i] << endl;
}
cout << "\nEnter your choice:\n MENU\n[P]osition\n[R]everse\n[A]verage\n[S]earch\n[Q]uit\n";
cin >> c;
cout << "\nYou chose option " << c << endl;
switch (c)
{
case 'P':
cout << "This is the array with each element's position" << endl;
for (i = 1; i <= 5; i++)
{
cout << "Value at position " << i << " is " << array[i] << endl;
}
break;
case 'R':
cout << "The array in reverse order is:" << endl;
for (i = 5; i >= 1; i--)
{
cout << array[i] << endl;
}
break;
case 'A':
cout << "The average of the array is:" << endl;
for (i = 1; i <= 5; i++)
{
average = average + array[i];
}
cout << average / 5;
break;
case 'S':
cout << "Enter a number to search the array:" << endl;
cin >> num;
x = 0;
for (i = 1; i <= 5; i++)
{
if (array[i] == num)
{
x = 1;
break;
}
}
if (x == 1)
{
cout << num << " is found at position " << i;
}
else
{
cout << "This number is not in the array";
}
break;
case 'Q':
exit(1);
return 0;
}
}
您可以像這樣將代碼放入 while 循環中:
int array[5];
int i, num, x;
char c = '\0';
float average = 0;
srand(time(0)); //This makes the set of numbers differnet every time
for (i = 1; i <= 5; i++)
{
array[i] = (rand() % 5) + 15;
}
while (c != 'q')
{
cout << "Array elements are: \n";
for (i = 1; i <= 5; i++)
{
cout << array[i] << endl;
}
cout << "\nEnter your choice:\n MENU\n[P]osition\n[R]everse\n[A]verage\n[S]earch\n[Q]uit\n";
cin >> c;
cout << "\nYou chose option " << c << endl;
switch (c)
{
case 'P':
cout << "This is the array with each element's position" << endl;
for (i = 1; i < 5; i++)
{
cout << "Value at position " << i << " is " << array[i] << endl;
}
break;
case 'R':
cout << "The array in reverse order is:" << endl;
for (i = 5; i >= 1; i--)
{
cout << array[i] << endl;
}
break;
case 'A':
cout << "The average of the array is:" << endl;
for (i = 1; i <= 5; i++)
{
average = average + array[i];
}
cout << average / 5;
break;
case 'S':
cout << "Enter a number to search the array:" << endl;
cin >> num;
x = 0;
for (i = 1; i <= 5; i++)
{
if (array[i] == num)
{
x = 1;
break;
}
}
if (x == 1)
{
cout << num << " is found at position " << i;
}
else
{
cout << "This number is not in the array";
}
break;
case 'Q':
exit(1);
return 0;
}
}
所以代碼只有在c
不等於q
時才會運行。 希望這可以幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.