如何让do-while循环在用户想要再次运行的情况下再次运行?



当使用do-while, while或for循环时,我似乎总是在尝试询问用户是否想再次运行函数后不断地得到无限循环。

#include <iostream>
int main()
{
char choice = 'y';

while (choice == 'y')
{
// Do something

// Exits while loop

}

std::cout << "Would you like to do it again?" << std::endl;

std::cin >> choice;
}

是否有我忘记的代码行?

在这种情况下,最好用while循环代替do-while循环。例如

#include <iostream>
int main()
{
char choice = 'y';

do
{
// Do something

std::cout << "Would you like to do it again?" << std::endl;

std::cin >> choice;
} while ( choice == 'y' || choice == 'Y' );

}

因为问题(和input read)应该在while循环内:

#include <iostream>
int main()
{
char choice = 'y';

while (choice == 'y') {
// Do something
std::cout << "Would you like to do it again?" << std::endl;
std::cin >> choice;
}
}

更新:根据Remy的建议添加do-while环。

int main()
{
char choice;
do {
// Do something
std::cout << "Would you like to do it again?" << std::endl;
std::cin >> choice;
} while (choice == 'y');
}

相关内容

  • 没有找到相关文章

最新更新