【问题标题】:for loop skipping getlinefor循环跳过getline
【发布时间】:2012-02-01 15:35:30
【问题描述】:

大家好,我正在做关于结构化数据的编程作业,我相信我了解结构的工作原理。

我正在尝试读取学生姓名、身份证号(A-Numbers)及其余额的列表。

不过,当我编译我的代码时,它会在第一次读取所有内容,但第二次循环时,每次之后,它都会提示输入用户名但跳过 getline 并直接进入 A-Number 和 A -数字条目。

任何帮助将不胜感激。只是想弄清楚每次循环时如何使 getline 工作。

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;


int main(){
    const int maxStudents = 30;
    struct Students{
        string studentName;
        int aNumber;
        double outstandingBalance;};

    Students students[maxStudents];

    for(int count = 0; count < maxStudents-1; count++)
    {
        cout<<"Student Name:";
                cin.ignore();
        getline(cin,students[count].studentName);
        cout<<"\nA-Number:";
        cin>>students[count].aNumber;
        if(students[count].aNumber == -999)
            break;
        cout<<"\nOutstanding Balance:";
        cin>>students[count].outstandingBalance;
    }

    cout<<setw(20)<<"A-Number"<<"Name"<<"Balance";

    for(int count2 = 29; count2 >= maxStudents-1; count2--)
        cout<<setw(20)<<students[count2].aNumber<<students[count2].studentName<<students[count2].outstandingBalance;


    system("pause");
    return 0;
}

【问题讨论】:

  • 你不能只使用cin&gt;&gt;students[count].studentName;。顺便说一句
  • @Neox - 如果学生的名字中有空格,则不会,就像“John Hancock”那样。

标签: c++ loops for-loop struct


【解决方案1】:

查找C++ FAQ on iostreams

第 15.6 项专门处理您的问题(“为什么我的程序在第一次迭代后忽略了我的输入请求?”),但您可能会发现整个页面很有用。

HTH,

【讨论】:

    【解决方案2】:

    cin.ignore();

    在循环结束时。

    【讨论】:

      【解决方案3】:

      您所做的事情不起作用的原因是“>>”运算符 第一次通过不要提取尾随'\n',下一个getline 看到它,并立即返回一个空行。

      简单的答案是:不要混用 getline&gt;&gt;。如果输入是 面向行,使用getline。如果需要解析行中的数据 使用&gt;&gt;,使用getline读取的字符串初始化一个 std::istringstream,并在上面使用&gt;&gt;

      【讨论】:

      • 我明白我做错了什么,但你的其余回答让我完全不知道你想告诉我做什么。
      • 我使用了 cin.ignore();在 getline 解决我的问题之前。
      • @sircrisp:从包含读取的行的std::string 创建一个std::istringstream。然后,您可以像使用 std::cin 一样从流中提取空格分隔的项目:istr &gt;&gt; item;
      • 不错!谢谢你的提示。由于家庭作业的要求,不能将其用于此特定程序。必须是字符串。
      • 另外:每次输入后检查流的状态。如果有人在应该输入数字时输入"abc",您的代码会表现得非常有趣。 (事实上​​,这是getline/istringstream 方法的一个主要好处。这种情况下的错误将出现在循环本地的istringstream 上。无论发生什么,主要输入保持在线同步。)
      【解决方案4】:

      问题在于混合cingetline。格式化输入(使用 >> 运算符)和未格式化输入(getline 就是一个例子)不能很好地配合使用。你绝对应该阅读更多关于它的信息。 Click here for more explanation

      这里是您的问题的解决方案。 cin.ignore(1024, '\n'); 是关键。

      for(int count = 0; count < maxStudents-1; count++)
      {
          ...
          cout<<"\nOutstanding Balance:";
          cin>>students[count].outstandingBalance;
          cin.ignore(1024, '\n');
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多