简体   繁体   English

cin.ignore()在程序中不起作用

[英]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. 我的程序假定输出First Middle Last name并忽略输入中的。 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 ). ignore函数作用于当前输入流(例如cin ),并丢弃第一个参数中指示的字符数,直到找到作为第二个参数给出的分隔符​​(默认为EOF )。

So, the way you have it, cin.ignore(','); 因此,您拥有的方式cin.ignore(','); will ignore 44 characters until EOF, after you have printed the inputs given. 在打印了给定的输入之后,它将忽略44个字符,直到EOF。 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, ','); 如果要跳过逗号,则需要调用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). 这将跳到输入中的下一个逗号(最多100个字符)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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