简体   繁体   中英

cin.ignore() is not working in program

My program is suppose to output First Middle Last name and ignore the , that is in the input. But in my program the comma is still in my output so obviously I am missing something.

#include <iostream>
#include <string>
using namespace std;
char chr;
int main()
{
string last, first, middle;
cout<< "Enter in this format your Last name comma First name Middle name."<<endl;   //Input full name in required format
cin>>last;                                                                          //receiving the input Last name 
cin>>first;                                                                         //receiving the input First name
cin>>middle;                                                                        //receiving the input Middle name
cout<<first<<" "<<middle<< " " <<last;                                              //Displaying the inputed information in the format First Middle Last name
cin.ignore(',');                                                                    //ignoring the , that is not neccesary for the new format
cin>>chr;

return 0;
}

The ignore function acts on the current input stream (eg cin ), and it discards as many characters as indicated in the first argument, until it finds the delimiter given as the second argument (default as EOF ).

So, the way you have it, cin.ignore(','); will ignore 44 characters until EOF, after you have printed the inputs given. This is almost certainly NOT what you wanted to do.

If you want to skip past a comma, then you will want to call cin.ignore(100, ','); between the input of the last name and the input of first name. That will skip to the next comma in the input (up to 100 characters).

You can pick commas from stream:

std::istream& comma(std::istream& in)
{
    if ((in >> std::ws).peek() == ',')
        in.ignore();
    else
        in.setstate(std::ios_base::failbit);
    return in;
}

int main()
{
    string last, first, middle;

    cin >> last >> comma >> first >> comma >> middle;

    cout << first << " " << middle << " " << last;
}

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