gpt4 book ai didi

带有计数的 for 和 while 循环中的 C++ 哨兵。陷入无限循环

转载 作者:行者123 更新时间:2023-11-28 02:20:16 33 4
gpt4 key购买 nike

我一直陷入代码的无限循环中。我必须做到这一点,这样您就可以使用哨兵“​​q”退出,但迭代次数不得超过 20 次。任何帮助将不胜感激,因为我只是编程新手。

#include <iostream>

using namespace std;

int main()
{
int option; // If new member or existing member or exit
char SENTINEL = 'q';
while(option != SENTINEL)
{
for(int count = 0; count <= 20; count++)
{
// Display menu
cout << "Welcome to the forum.\n";
cout << "Are you:\n";
cout << "1. A new member\n";
cout << "2. An existing member" << endl;
cout << "To exit press 'q'\n";
cin >> option;

if (option == 1)
{
char new_name[20]; // Array to hold new member

cout << "You're a new member.\n";
cout << "Please enter your first name followed ";
cout << "by your last name.\n";
cout << "Then press return.\n";

cin >> new_name; // User enter their name
}
else if (option == 2)
{
cout << "You're an existing member." << endl;
}
}
}
}

最佳答案

您需要执行以下操作:

  1. 摆脱 while 循环。您需要使用一个具有多个条件的循环,或者在循环内从它break
  2. option 设为 char 而不是 int。将 optionSENTINEL 进行比较没有意义,因为它们是不同的类型。将 option 设为 char 将解决此问题。
  3. 使用 string 类而不是包含 20 个元素的 char 数组。名字和姓氏超过 20 个字符的任何人都会导致缓冲区溢出。 string 更安全,如果需要会自动扩展。

#include <iostream>
#include <string>

using namespace std;

int main()
{
char option; // If new member or existing member or exit
char SENTINEL = 'q';

for(int count = 0; count <= 20; count++)
{
// Display menu
cout << "Welcome to the forum.\n";
cout << "Are you:\n";
cout << "1. A new member\n";
cout << "2. An existing member" << endl;
cout << "To exit press 'q'\n";
cin >> option;
cin.get(); // discard newline char

if (option == '1')
{
string new_name; // string to hold new member

cout << "You're a new member.\n";
cout << "Please enter your first name followed ";
cout << "by your last name.\n";
cout << "Then press return.\n";

getline(cin, new_name); // User enter their name
}
else if (option == '2')
{
cout << "You're an existing member." << endl;
}
else if (option == SENTINEL) {
break; // break from the loop
}
}
}

关于带有计数的 for 和 while 循环中的 C++ 哨兵。陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793496/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com