作业:
程序应该要求用户输入一个正数并显示从 1 到输入值的所有数字。如果数字不是正数,则应显示一条错误消息,要求用户重新输入数字。
我的具体问题:
对于我的程序,如果用户输入了一个错误的数字然后重新输入一个正数,它不会显示从1到输入值的所有数字。程序刚刚结束。
#include <iostream>
using namespace std;
int main()
{
int userChoice;
int i = 1;
cout << "Enter a positive integer" << endl;
cin >> userChoice;
if (userChoice > 0)
{
for (i = 1; i <= userChoice; i++)
{
cout << "Loop 1:" << endl;
cout << i << endl;
}
}
else if (userChoice < 0)
cout << "Please re - enter" << endl;
cin >> userChoice;
system("pause");
return 0;
}
最佳答案
您的程序顶部需要某种循环,它会不断请求输入,直到用户提供有效的内容。看起来像是家庭作业,所以我将提供伪代码,而不是确切的代码:
std::cout << "Enter a number:\n";
std::cin >> choice;
while (choice wasn't valid) { // 1
tell the user something went wrong // 2
ask again for input in basically the same way as above // 3
}
// after this, go ahead with your for loop
实际上可以避免步骤 3 的重复,但我担心这可能会让您有些困惑,所以一行重复并不是什么大问题。
顺便说一句,您可能希望重新考虑您对通常被认为是不良做法的使用:using namespace std;
和 endl
. (免责声明 - 这些是观点,并非确凿的事实)。
关于c++ - For 循环 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56629920/