簡體   English   中英

C ++ while循環和getline問題

[英]C++ while loop and getline issue

我正在創建的程序中的while循環出現問題。 基本上是假設在輸入ctrl + D之前要求用戶輸入(這些條目最終將存儲在數組中,但是我只是在嘗試執行該步驟之前先檢查輸出)

問題是當我退出變量時,第一行丟失了。

int main()
{
    string title;
    string url;
    string comment;
    double length = 0.0;
    int rating = 0;
    string sort_method;

    cin >> sort_method;

while(getline(cin,title))
{
        getline(cin, title);
        getline(cin, url);
        getline(cin, comment);
        cin >> length;
        cin >> rating;
        cin.ignore();

}
    cout << title << endl;
    cout << url << endl;
    cout << comment << endl;
    cout << length << endl;
    cout << rating << endl;

感謝您的幫助。

我編譯了您的代碼。 您沒有在while主體中發出任何命令來中斷while。

(1)您已經使用了cin.ignore(); 函數而不是使用此函數(cin.ignore(256,'\\ n'))。 這有助於為下一個輸入獲取cin的空緩沖區。
(2)您需要關注應該中斷循環的條件。 我在這里cnsidering您的第一個輸入變量標題。 在while循環中,while條件之后的第一個語句應該是(諸如title(Mr。Miss。Mrs.)之類的特定決策條件)之類的if(title!=“ Mr.” || title!=“ Miss。” || title !=“夫人。”)比休息; (3)用於將所有輸入顯示為輸出。您應該存儲它們。 如果您不想這樣做,請將所有cout語句放入while循環內。

#include <iostream>
using namespace std;
int main()
{
   string title;
   string url;
   string comment;
   double length = 0.0;
   int rating = 0;
   string sort_method;
   cin >> sort_method;

   while(getline(cin,title))
   {
       // use operator overloading
       if(title!="Mr."||title!="Mrs."||title!="Miss.")
            break;
       getline(cin, url);
       getline(cin, comment);
       cin >> length;
       cin >> rating;
       cin.ignore(256,'\n');
       cout << title << endl;
       cout << url << endl;
       cout << comment << endl;
       cout << length << endl;
       cout << rating << endl;
       cout<<"for quit press 'q'"<<endl;
   }
   return 0;
}

希望這可以幫助您...

暫無
暫無

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

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