简体   繁体   English

每当我运行它时,我的程序就会进入无限循环,但只有当我输入无效数字然后输入字符或字符串时

[英]My program goes into an infinite loop whenever I run it, but only whenever I enter an invalid number then a character or string

In my program, I am trying to validate the users input an make sure that the only thing they can put in is a number between 1998-2019.在我的程序中,我试图验证用户输入,并确保他们唯一可以输入的是 1998-2019 之间的数字。 The problem is, whenever I input a number first(and only a number), the program runs fine but if I put an invalid number then a character or string, the program goes into an infinite loop.问题是,每当我先输入一个数字(并且只输入一个数字)时,程序运行良好,但如果我输入一个无效数字,然后输入一个字符或字符串,程序就会进入无限循环。 The program also runs whenever I type in a character or string first then a number, but if I type in a character after I have typed in a number, it enters an infinite loop.每当我先输入字符或字符串然后输入数字时,该程序也会运行,但如果我在输入数字后输入字符,则会进入无限循环。 Does anybody know why this is occurring or have a possible solution?有人知道为什么会发生这种情况或有可能的解决方案吗?

This is the code causing the problem:这是导致问题的代码:

   while (userInputYear < 1998 && userInputYear != -99 || userInputYear > 2019)
    {
        cout << "\nPlease enter an integer between 1998 and 2019: ";
    
        while (!(cin >> userInputYear)) 
        {
            cin.clear();
            cin.ignore(1000, '\n');
            cout << "\nPlease enter an integer between 1998 and 2019: ";
        }
    }

When I use the above code this is what is displayed:当我使用上面的代码时,显示的是:

National Championship Inquiry全国冠军查询

Reading the input file...读取输入文件...

Enter a year between 1998 - 2019 to find the champion (press -99 to stop): 2019输入1998-2019之间的年份查找冠军(按-99停止):2019

The LSU Tigers were the National Champions in 2019路易斯安那州立大学老虎队是 2019 年的全国冠军

Enter a year between 1998 - 2019 to find the champion (press -99 to stop): two thousand输入1998-2019之间的年份找冠军(按-99停止):两千

Please enter an integer between 1998 and 2019: Please enter an integer between 1998 and 2019: -99请输入 1998 年至 2019 年之间的 integer:请输入 1998 年至 2019 年之间的 integer:-99

Press any key to continue.按任意键继续。 . . . .

This is my entire program:这是我的整个程序:

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

class Champs
{
private:
    ifstream inChamps;      //input file

    int ayear[22];          //arrays
    string aname[22];

    int userInputYear = 0;              //holds value for user input


    void openFile();
    void testFile();
    void readFile();
    void validate();
    void yearName();
    void closeFile();

public:
    void driver()
    {
        openFile();
        readFile();
        yearName();
        closeFile();
    }
};

void Champs::openFile()                         //opens input file
{
    inChamps.open("NationalChampionship.txt");      
}

void Champs::readFile()
{
    if (inChamps.is_open())
    {
        cout << "National Championship Inquiry" << endl << endl;
        cout << "Reading the input file..." << endl << endl;
    }
    else
        testFile();
}

void Champs::testFile()
{
    cout << "Unable to open input file";
    exit(1);
}

void Champs::yearName()
{
    for (int i = 0; i < 22; i++)
    {
        int year;
        inChamps >> year;
        ayear[i] = year;

        string name;
        getline(inChamps >> ws, name);
        aname[i] = name;
    }

    

    //validate input
    
    bool on = true;
    while (on == true)
    {
        cout << "Enter the year: ";
        cin >> userInputYear;
        validate();
    
        if (userInputYear == -99)
            {
                on = false;
                break;
            }
        for (int i = 0; i < 22; i++)
        {
            
            if (userInputYear == ayear[i])
            {
                cout << "\nIn " << userInputYear << " the " << aname[i] << " won the national championship.\n\n";
            }
            
        }
    }
}

void Champs::validate()
{
    while (userInputYear < 1998 && userInputYear != -99 || userInputYear > 2019)
{
    cout << "\nPlease enter an integer between 1998 and 2019: ";

    while (!(cin >> userInputYear)) 
    {
        cin.clear();
        cin.ignore(1000, '\n');
        cout << "\nPlease enter an integer between 1998 and 2019: ";
    }
}

void Champs::closeFile()
{
    inChamps.close();
}

int main()
{
    Champs obj;
    obj.driver();
    system("pause");
    return 0;
}

I am still very new to c++ but I feel like this is something simple I am missing.我对 c++ 还是很陌生,但我觉得这很简单,我很想念。 Any help or suggestions are appreciated.任何帮助或建议表示赞赏。 Also,还,

In the second while loop, you are going to into the infinite loop because there are invalid characters left in the buffer.在第二个 while 循环中,您将进入无限循环,因为缓冲区中剩余无效字符。 When cin encounters invalid characters it goes into an error state, when this happens you must: 1.You have to test for this error state.当 cin 遇到无效字符时,它会进入错误 state,发生这种情况时您必须: 1.您必须测试此错误 state。 2.You have to clear the error state. 2.您必须清除错误 state。 3. You have to either alternatively handle the input data that generated the error state, or flush it out and reprompt the user. 3. 您必须选择处理生成错误 state 的输入数据,或者将其清除并重新提示用户。 Something like this would me more appropriate:这样的事情我会更合适:

while (userInputYear < 1998 && userInputYear !=-99 || userInputYear > 2019)
    {
        cout << "Please enter an integer between 1998 and 2019: ";
        while(!(cin >> userInputYear)) {
          cin.clear();
          cin.ignore(1000, '\n');
          cout << "Please enter an integer between 1998 and 2019: ";
        }
        cout << endl;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 每当我尝试读取字符串时,我的 C++ 程序就会崩溃 - My C++ program crashed whenever I try to read the string 输入字符时,为什么程序会有无限循环? - Why does my program have an infinite-loop when I enter in a character? 每当我运行这个程序 C++ 时,我都会出错。 我做错了什么 - I get error whenever I run this program C++. What I am doing wrong 我试图像输出一样显示全名,但是每当我点击进入程序时,只打印出 1 个单词而不是 2 个单词 - im trying to display the full name like the output did , but whenever i hit enter the program just print out 1 word rather than 2 word 每当我尝试在Codelite中运行我的项目时,我所做的任何更改似乎都会被忽略 - Whenever I try to run my project in codelite, any changes I've made seem to be ignored 每当我运行我的 OpenGL 代码时,我都会出现白屏和崩溃 - Whenever I run my OpenGL Code I get a white screen and a crash 每当我尝试初始化 Employer 对象时,我的程序都会给出未处理的异常错误 - My program gives an Unhandled exception error whenever I try to initialize a Employer object 每当我运行代码时,我的默认情况总是与其他情况一起运行(C ++) - Whenever i run the code my default case always runs with the other cases (C++) 我正在尝试在 Vscode 上执行此代码,但每当我运行此代码时,它不会获取字符的值,而只是显示一个随机数 - I'm trying to execute this code on Vscode but whenever I'm running this it's not taking the value of character but just showing a random number 我总是在运行该程序时遇到无限循环。 - I always run into a infinite loop on running this program.
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM