赋值:

程序应该要求用户输入一个正数并显示从 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/

10-11 22:35
查看更多