-1

I'm making a simple data management system which have 3 services

  1. Add a student.

  2. View a student information.

  3. Delete a student

The code looks like this :

#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);
}

It works fine but when I give a input in string it keeps on looping without giving me a chance to give an input again.

Before giving input as string:

Before giving input as string

After giving input in string:

After giving input in string

Please help me fix this weird error.

PS:- The code isn't complete yet.

Sorry for bad English.

fefe
  • 3,342
  • 2
  • 23
  • 45
  • 2
    `Serv!=Add || Serv!=View || Serv!=Del` This will be always true, since no `Serv` can be *equal* to all three values. Guess you meant `&&` instead. `|| !cin` Hard to guess what this is doing here. – dxiv Dec 22 '20 at 05:04
  • In the third line of your loop, you also manually set Service to 0, which will override the user input you got earlier. – EnigmaticBacon Dec 22 '20 at 05:26
  • @dxiv Literally I noticed it later. And BTW `||!cin` in this situation I wanna say if input!=int continue again – Atif Iqbal Dec 22 '20 at 06:58
  • @Atif Iqbal See [this question](https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input) for implementing that. – Rane Dec 22 '20 at 07:19

1 Answers1

0

The !cin in your loop condition returns true if the stream is in an error state (eg. reading an int failed). Not to mention the strange != in your conditions that @dxiv mentioned. What you probably meant was the following:

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);
Rane
  • 321
  • 2
  • 6