繁体   English   中英

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

[英]cin.ignore() is not working in program

我的程序假定输出First Middle Last name并忽略输入中的。 但是在我的程序中,逗号仍然出现在我的输出中,因此很明显我遗漏了一些东西。

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

ignore函数作用于当前输入流(例如cin ),并丢弃第一个参数中指示的字符数,直到找到作为第二个参数给出的分隔符​​(默认为EOF )。

因此,您拥有的方式cin.ignore(','); 在打印了给定的输入之后,它将忽略44个字符,直到EOF。 几乎可以肯定这不是您想要做的。

如果要跳过逗号,则需要调用cin.ignore(100, ','); 输入姓氏和名字之间。 这将跳到输入中的下一个逗号(最多100个字符)。

您可以从流中选择逗号:

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