大家好,我正在做关于结构化数据的编程任务,我相信我了解结构是如何工作的。
我正在尝试读取学生姓名、身份证号(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 许可协议
你所做的事情不起作用的原因是 ‘>>’ 运算符第一次没有提取尾随
'\n'
,下一个getline
看到它,并且立即返回空行。简单的答案是:不要混合
getline
和>>
。如果输入是面向行的,请使用getline
。 If you need to parse data in the line using>>
, use the string read bygetline
to initialize astd::istringstream
, and use>>
在上面。