0

I'm trying to create a struct and collect its inputs from the user with a while loop, however on the second iteration it just seems to skip past the inputs.

#include <iostream>
#include <list>

struct Student {
    std::string name;
    std::string course;
    float mark;
};

int main() {

    std::list<Student> students;

    while (students.size() < 2) {
        Student student;

        std::cout << "Student Name:" << std::endl;
        std::getline (std::cin, student.name);
        std::cout << "Course and Mark:" << std::endl;
        std::cin >> student.course >> student.mark;

        students.push_back(student);
    }

    for(auto const& student: students) {
        std::cout << student.name << std::endl;
    }

    return 0;
}

The output looks like so:

Student Name:
Ari Stackoverflow
Course and Mark:
course543 56.2
Student Name:   <---- skipped :(
Course and Mark:
Steve Jobs

As you can see, one the second iteration it skips over getting the name, not sure why.

Ari
  • 2,499
  • 2
  • 24
  • 54

1 Answers1

1

The problem here is that when you press "Enter" after your second line of input, that newline is fed to std::getline(std::cin, student.name); on the next iteration. And so students[1].name would be an empty string.

To get around this, add std::cin.ignore() or std::cin.get() after reading your second line. This tells cin to ignore the newline.

TrebledJ
  • 7,200
  • 7
  • 20
  • 43
  • This worked thank you! I still don't entirely understand it however, will need to experiment some more. – Ari Mar 21 '21 at 07:18