简体   繁体   中英

C++ ignore and clear buffer

    int position;
    afile.open("EmployeeInfo.dat", ios::in | ios::binary);   

    char name[80];
    cout << "\nEdit Employee Info" << endl;
    cout << "---------------------" << endl;
    cout << "New Employee Username: ";
        cin.clear();
        cin.ignore(100, '\n');
        cin.getline(name, 80);
    bool flag = true;

hi all this is a code fragment of my program that i'm currently doing. most of the functionality are fine, with the exception that i need to press Enter twice to receive the getline data. can anyone point out to me where im doing wrongly?

last input prior to this is a integer input using cin >> choice; going into a switch. i do not have any errors with other functions even though they are doing the exact same thing. literally exact.

for eg. no errors with the following

afile.open("EmployeeInfo.dat", ios::in | ios::binary);   

char name[80];
cout << "\nAdd Employee Info" << endl;
cout << "---------------------" << endl;
cout << "New Employee Username: ";
    cin.clear();
    cin.ignore(100, '\n');
cin.getline(name, 80);

Okay here's the surrounding codes.

the function is called in another function

    cout << "Your Choice: ";
    cin >> choice;

    switch(choice)
    {
        case 1: cout << "Create Holiday Package" << endl;
        break;
        case 2: cout << "Delete Holiday Package" << endl;
        break;
        case 3: cout << "Edit Holiday Package" << endl;
        break;
        case 4: addEmployee(afile, num, e);
        break;
        case 5: delEmployee(afile, num, e);
        break;
        case 6: editEmployee(afile, num, e);
        break; ....// to be continue case
  }//end case

and this is the interaction i have with the cmd

Welcome to Employee Login Screen

Please Enter Username: Daniel Roberts

Please Enter Password: Daniel1234

Login successful

General Manager Menu

1)Create Holiday Package

2)Delete Holiday Package

3)Edit Holiday Package

4)Create a Staff Account

5)Delete a Staff Account

6)Edit a Staff Account

7)View Stats of Booking Packages

8)Quit

Your Choice: 6

Edit Employee Info


New Employee Username: John Smith

<- weird space here that i need to press enter to get rid of

Enter new name:

The problem is the cin.ignore() call, it will read until it has either read 100 characters or one of those characters are a newline. So to satisfy it you have to enter eg a newline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM