尝试以字符串格式输入时间时,会导致无限循环

问题描述 投票:0回答:1

我开始学习 C++ 编程。任务是让用户输入小时数。但是,当尝试以文本字符串格式输入时间时,它开始无限执行循环,并显示消息“小时值不正确!”。

do{
    cout << "Enter hours: ";
    cin >> hours;
    if(cin.fail())
    {
        cin.ignore(10, '\n');
        cin.clear();
        cout << "The value of hours is incorrect!" << endl;
        continue;
    }
    if (hours > 0 && hours < 23) { break; }
    cout << "The value of hours must be between 0 and 23!" << endl;
}while(true);

我尝试使用

cin.ignore(numeric_limits<streamsize>::max(), '\n');
代替
cin.ignore(10, '\n');
,但没有帮助。由于某种原因
cin >> hours;
没有按我的预期工作,但我不知道问题是什么。

c++ boolean runtime-error do-while cin
1个回答
0
投票

就其价值而言,我从不使用

cin
。绝不。我总是使用
getline
到字符串中并进行自己的解析。这使您可以更好地控制如何处理奇怪的数据。

您收到的一些评论应该会有所帮助。你们的法定工作时间范围有缺陷。它应该 >= 0 且 <= 23, probably.

© www.soinside.com 2019 - 2024. All rights reserved.