Why using string for input values in C++ doesn’t allow me to use spacing in the input? [duplicate]

  c++, class

I wrote the below code to get the user name and some values to print the GPA, the problem is that when I want to enter 2 separate names, it terminates the program.

Also, for the GPA output, it should be 3.38 not 3.67, is it a mistake in my formula?

Input code:

#include <iostream>
#include <string>
using namespace std;

class Student {
    double points[4];
    int creditHour[4];
    string name;
public:
    Student(string na){
            name = na;
    }
    
    void GetPointers(void){
        int i;
        for (i = 0; i < 4; i++) {
        cout << "Points for subject " << i + 1 << ": ";
        cin >> points[i];
        cout << "Credit Hour for subject " << i + 1 << ": ";
        cin >> creditHour[i];
        }
    }
    
    void Display(){
    double t;
        cout << "Hello " << name << endl;
      t = CalculateGPA();
        cout << "Your current GPA is " << t << endl;
    }
    
private:
    double CalculateGPA(void){
        double sum1=0, sum2=0, total=0;

        for (int i = 0; i < 4 ; i++) {
        sum1 += (points[i] * creditHour[i]);
        sum2 += creditHour[i];
    total = sum1 / sum2;

        return total;
        }
    }
};

int main() {
    string n;
    cout << "Your name?: ";
    cin >> n;
    Student stud(n);
    cout << "Key in points for 4 subjects" << endl;
    stud.GetPointers();
    cout << endl;
    stud.Display();

    return 0;
}

Output is terminated and became messy when I entered 2 names:

Your name?: name1 name2
Key in points for 4 subjects
Points for subject 1: Credit Hour for subject 1: Points for subject 2: Credit Hour for subject 2: Points for subject 3: Credit Hour for subject 3: Points for subject 4: Credit Hour for subject 4: 
Hello name1
Your current GPA is 0

And when I enter one name, the program works well but the GPA value should be 3.38:

Your name?: name
Key in points for 4 subjects
Points for subject 1: 3.67
Credit Hour for subject 1: 4
Points for subject 2: 4
Credit Hour for subject 2: 3
Points for subject 3: 2.67
Credit Hour for subject 3: 4
Points for subject 4: 3.33
Credit Hour for subject 4: 4

Hello name
Your current GPA is 3.67

Source: Windows Questions C++

LEAVE A COMMENT