【问题标题】:How To Fix Unexpected Loop In C++如何修复 C++ 中的意外循环
【发布时间】:2021-03-31 20:09:41
【问题描述】:

我正在制作一个包含 3 个服务的简单数据管理系统

  1. 添加学生。

  2. 查看学生信息。

  3. 删除学生

代码如下所示:

#include <iostream>
using namespace std;
enum Services
{
    Add=1,
    View,
    Del
};
class Student
{
public:
    string Name;
    int Age;
    string Gender;
    int Class;
    
    Student(string Name,string Gender,int Age,int Class)
    {
        this->Name=Name;
        this->Gender=Gender;
        this->Age=Age;
        this->Class=Class;
    }
};
int main()
{
    //Bio Variables
    string Name;
    string Gender;
    int Age;
    int Class;
    
    std::cout<<"•Add A Student [PRESS 1]\n•View Student's Information [PRESS 2]\n•Delete A Student [PRESS 3]"<<endl;
    //Creating Instance Of Service ENUM
    Services Serv;
    do
    {
        cout<<"\nWhich Service Do You Want To Access :";
        int Service;
        cin>>Service;
        Service=0;
    }while(Serv!=Add || Serv!=View || Serv!=Del || !cin);
}

它工作正常,但是当我在字符串中输入时,它会继续循环,而没有给我再次输入的机会。

在以字符串形式输入之前:

输入字符串后:

请帮我解决这个奇怪的错误。

PS:- 代码尚未完成。

抱歉英语不好。

【问题讨论】:

  • Serv!=Add || Serv!=View || Serv!=Del 这总是正确的,因为没有Serv 可以等于 与所有三个值。猜猜你的意思是&amp;&amp;|| !cin 很难猜到这是在做什么。
  • 在循环的第三行中,您还手动将 Service 设置为 0,这将覆盖您之前获得的用户输入。
  • @dxiv 从字面上看,我后来注意到了。顺便说一句||!cin 在这种情况下我想说如果输入!=int 再次继续
  • @Atif Iqbal 请参阅 this question 以实现该功能。

标签: c++ c++11 visual-c++ c++17


【解决方案1】:

如果流处于错误状态(例如,读取int 失败),循环条件中的!cin 将返回true。更不用说@dxiv 提到的你的条件中奇怪的!=。您的意思可能是:

do
{
    cout << "\nWhich Service Do You Want To Access: ";
    int Input = 0;
    cin >> Input;
    Serv = static_cast<Service>(Input);
} while (cin && Serv >= Add && Serv <= Del);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多