4 c++
分配:
该程序应要求用户输入一个正数并显示从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;
}
Run Code Online (Sandbox Code Playgroud)
您需要在程序顶部进行某种循环,直到用户提供有效的内容之前,该循环一直在请求输入。它看起来像是一项家庭作业,因此我将提供伪代码,而不是确切的代码:
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
Run Code Online (Sandbox Code Playgroud)
实际上,可以在此处避免步骤3的重复,但是我担心这可能会使您感到困惑,因此,一条重复的行实际上并不是什么大问题。
顺便说一句,您可能希望重新考虑对通常被认为是不良做法的使用:using namespace std;和endl。(免责声明-这些是观点,不是事实)。