Search This Blog

Friday, December 30, 2011

How to use getline() and switch() together in c++

Add the line cin.ignore(); before the getline.
Main problem is that the stream operator >> leaves the newline in the stream so when you try to use getline it reads an empty line. ignore() will chew up the newline and let you read the string you expect.

Here is example:::

#include
#include
#include
using namespace std;
const int size=100;
const int length=50;
class list
{
   
    char name[size][length];
    //string name[size];
    int number[size];
    int count;
    char newName[length];
    //string newName;
   
    public:
    void CNT(void)
    {
        count =0; //initializes count to zero
    }

    void initialize(void);
    void check_list(void);
    void add_name(void);   
};

void list::initialize(void)
{
    int i;
    for(i=0;i    {
        number[i]=0;
        strcpy(name[i],"default");
       
    }
}

void list::add_name(void)
{   
    cin.ignore();
    cout<<"\n"<<"Enter your FULL NAME to add in list : ";
    //cin>>name[count];
    cin.getline(name[count],length);
    //cin.getline(name[count],length);
    cout<<"\n"<<"Enetr your name's associated number : ";
    cin>>number[count];
    count++;
    //cout<<"\n"<    cout<<"\n"<<"========================================================================";
}

void list::check_list(void)
{
    int i;
    int logic=0;
    cin.ignore();
    cout<<"\n"<<"Enter your FULL NAME to check the associated number with it : ";
    //cin>>newName;
    cin.getline(newName,length);
    //cin.getline(newName,length);
    for(i=0;i    {
        if(strcmp(name[i],newName)==0)
        {
            cout<<"\n"<<"Number associated with your name is : "<            logic=1;
        }
        else
        {
            if(i==size-1 && logic==0)
            {
                cout<<"\n"<<"Ack!! Your name is not in the list. Enter option number 2 to add your name in list "<<"\n";
               
            }
        }
    }
   
    //cout<<"\n"<<"name is = "<
    cout<<"\n"<<"========================================================================";
}

int main()
{
    list user;
   
    user.CNT();
    user.initialize();
    //user.check_list();
    //user.add_name();
       
    int x;
    do
    {
        cout<<"\n"<<"You can do the following : "<<" Enter approperiate number  ";
        cout<<"\n"<<" 1 : to check your name and associated number in list ";
        cout<<"\n"<<" 2 : to add your name in list ";
        cout<<"\n"<<" 3 : to Quit ";
        cout<<"\n"<<" Please select your option ";
        cin>>x;
        switch(x)
        {
            case 1: user.check_list();
            break;
            case 2: user.add_name();
            case 3: break;
            default : cout<<"\n"<<"Error in input : Please select your correct option ";
        }   
    }while(x!=3);
   
   
    cout<<"\n";
    return 0;
   
}

No comments:

Post a Comment

Thank you