簡體   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