循环跳过getline [英] for loop skipping getline
问题描述
大家好,我正在做一个关于结构化数据的编程任务,我相信我理解结构是如何工作的。
我正在读取学生姓名列表,身份证号码(A-Numbers)及其余额。
当我编译我的代码时,它会在第一次读取所有内容,但是第二次循环和每一次后,它会提示输入用户名,但跳过getline并直接到A号码和A号码输入。
任何帮助,将不胜感激。只是试图找出如何让每一次循环进行getline工作。
#include< iostream>
#include< string>
#include< iomanip>
使用namespace std;
int main(){
const int maxStudents = 30;
struct Students {
string studentName;
int aNumber;
double outstandingBalance;};
学生学生[maxStudents]; (int count = 0; count< maxStudents-1; count ++)
{
cout<<<学生姓名:;
cin.ignore();
getline(cin,students [count] .studentName);
cout<<\\\
A-Number:;
cin>> students [count] .aNumber;
if(students [count] .aNumber == -999)
break;
cout<<\\\
Outstanding Balance:;
cin>> students [count] .outstandingBalance; (20)<< $ b cout (int count2 = 29; count2> = maxStudents-1; count2--)
cout< setw(20)<< students [count2] .aNumber< <学生[COUNT2] .studentName<<学生[COUNT2] .outstandingBalance;
system(pause);
返回0;
做不起作用的是'>>'第一次操作
不提取尾随'\ n'
,下一个 getline
看到它,并立即返回一个空行。
简单的答案是:不要混合 getline
和>>
。如果输入是
行定向,使用 getline
。如果您需要使用>>
解析
行中的数据,请使用 getline
初始化
std :: istringstream
,并使用>>
p>
Hello everyone I am doing a programming assignment on structured data and I believe I understand how structs work.
I am trying to read in a list of student names, ID numbers (A-Numbers), and their balances.
When I compile my code though, it will read everything in the first time around, but the second time around the loop and every time after, it prompts for the username but skips the getline and goes straight to A-Number and A-number entry.
Any help would be appreciated. Just trying to figure out how to make the getline work every time the loop goes around.
#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;
}
The reason what you're doing doesn't work is that the '>>' operators the
first time through don't extract the trailing '\n'
, the next getline
sees it, and returns immediately with an empty line.
The simple answer is: don't mix getline
and >>
. If the input is
line oriented, use getline
. If you need to parse data in the line
using >>
, use the string read by getline
to initialize a
std::istringstream
, and use >>
on it.
这篇关于循环跳过getline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!