簡體   English   中英

為什么getline在使用in循環時會忽略輸入的第一個字符?

[英]why getline ignoring first character of input while using in loop?

do
{
 system("cls");
        cout<<"Enter Item Name:"<<endl;
        cin.ignore();
        cin.getline(item_name,size);
        cout<<item_name<<endl;
        cout<<"Enter Item Price:"<<endl;
        cin>>item_price;
cout<<" Do You Want To Add More Item..?\nPress Y/N."<<endl;
char c;
c=getche();
}while(c=='y'||c=='Y');

這就是代碼的速度,實際上我在我的項目中正在使用它,我無法刪除cin.ignore,因為我必須從用戶那里獲取輸入,除非用戶按下任何其他字符而不是y

您知道標題中問題的答案。 通話

cin.ignore();

cin讀取下一個字符並將其丟棄。

我認為,您正在解決的真正問題是:如何終止循環?

這很簡單。 不要只比較一個字符。 比較整行。

do
{
   system("cls");
   cout << "Enter Item Name:"<<endl;
   cin.getline(item_name, size);
   cout << item_name << endl;
   cout << "Enter Item Price:" << endl;
   cin >> item_price;

   cout << "Do You Want To Add More Item..?\nPress Y/N." << endl;
   std::string ans;
   getline(cin, ans);

} while (ans == "y" || ans == "Y");

您可以使用以下內容。 使用cin.ignore(); c=getche();行之后c=getche();

char c;
do
{
        system("cls");
        cout<<"Enter Item Name:"<<endl;
        cin.getline(item_name,size);
        cout<<item_name<<endl;
        cout<<"Enter Item Price:"<<endl;
        cin>>item_price;
        cout<<" Do You Want To Add More Item..?\nPress Y/N."<<endl;
        c=getche();
        cin.ignore();
}while(c=='y'||c=='Y');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM