for循环跳过getline

新手上路,请多包涵

大家好,我正在做关于结构化数据的编程任务,我相信我了解结构是如何工作的。

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

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

任何帮助,将不胜感激。只是想弄清楚每次循环时如何使 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;
}

原文由 sircrisp 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 474
2 个回答

你所做的事情不起作用的原因是 ‘>>’ 运算符第一次没有提取尾随 '\n' ,下一个 getline 看到它,并且立即返回空行。

简单的答案是:不要混合 getline>> 。如果输入是面向行的,请使用 getline 。 If you need to parse data in the line using >> , use the string read by getline to initialize a std::istringstream , and use >> 在上面。

原文由 James Kanze 发布,翻译遵循 CC BY-SA 3.0 许可协议

cin.ignore();

在循环结束时。

原文由 Sayem Chaklader Gearspec 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏