0

Here is a small program to request and print some information. The problem point is storing name which may include spaces. My problem is that when reaches Enter your name it quickly moves to Enter your total marks without giving user an option to enter the name. Why is this happening?

#include <iostream>

using namespace std;

class StudentInformation {
protected:
    int studentID;
    string studentName;
    int totalMarks;
public:
    void input() {
        cout << "Enter your student id number: ";
        cin >> studentID;

        cout << "Enter your name: ";
        getline(cin, studentName);

        cout << "Enter your total marks";
        cin >> totalMarks;
    }

    void show() {
        cout << "Student ID: " << studentID << endl;
        cout << "Student Name: " << studentName << endl;
        cout << "Total Marks: " << totalMarks << endl;
    }
};

int main()
{
    cout << "Hello World!" << endl;

    StudentInformation stdinfo;

    stdinfo.input();
    stdinfo.show();

    return 0;
}

enter image description here

Sudhir Singh Khanger
  • 1,493
  • 2
  • 16
  • 32
  • For a thorough explanation: http://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction – chris Mar 30 '15 at 13:26

2 Answers2

3

Mixing use of cin >> with getline leads to problems.

  • cin >> studentID leaves the newline in the stream.
  • getline sees this straight away, so doesn't wait for new input.

I prefer using getline to read from the actual stream, and then using a stringstream for formatted extraction.

Or use ignore before getline:

std::cin >> ...; // leaves trailing whitespace and newline
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // eat next newline
std::getline(std::cin, ...);
BoBTFish
  • 17,936
  • 3
  • 49
  • 73
0

Just use cin.getline(studentName, size)

Yasir Majeed
  • 725
  • 3
  • 12