C ++ while循环和getline问题

问题描述 投票:0回答:1

我正在创建一个程序中的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;

我感谢任何帮助。

c++ loops while-loop getline
1个回答
0
投票

我编译了你的代码。你没有给任何命令,而身体打破了一会儿。

(1)你使用过cin.ignore();函数而不是这个使用它(cin.ignore(256,'\ n'))。这有助于为下一个输入获取cin的空缓冲区。 (2)你需要关注循环应该中断的条件。我在这里扼杀你的第一个输入变量标题。在while循环第一个语句后,条件应该是(一个特定的决定条件,如标题(先生。太太。))如果(标题!=“先生”||标题!=“小姐。”||标题!=“太太。”)而不是休息; (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;
}

希望这可能对你有所帮助......

© www.soinside.com 2019 - 2024. All rights reserved.