0

I am attempting to create a student object which takes the name, id, email, and three grades which are integers.

My code is quite simple and is as follows:

studentObj* newStudent = new studentObj;

cout << "Student First Name: ";
getline(cin, newStudent->name);
cout << "Student ID: ";
getline(cin, newStudent->id);
cout << "Student Email: ";
getline(cin, newStudent->email);
cout << "Grade 1: ";
cin >> newStudent->gradeOne;
cout << "Grade 2: ";
cin >> newStudent->gradeTwo;
cout << "Term Grade: ";
cin >> newStudent->termGrade;

cout << "Student Name: " + newStudent->name << endl;
cout << "Student ID: " + newStudent->id << endl;
cout << "Student Email: " + newStudent->email << endl;
cout << "Grade 1: " + newStudent->gradeOne << endl;
cout << "Grade 2: " + newStudent->gradeTwo << endl;

I assumed this would run flawlessly, but unfortunately that is not the case. It seems to be an issue mixing the getline() and cin.

The output is:

Student Name: Test Tester
Student ID: abcdef
Student Email: email@test.com
rade 1:
ade 2:
m Grade: 

I've tried adding cin.ignore(numeric_limits<streamsize>::max(),'\n'); in a few places, but no luck. Any suggestions? `

Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
Barry Tormey
  • 2,966
  • 4
  • 35
  • 55

2 Answers2

3

You can't add string literals to the integers (well, you can, but in your case you will not get anything meaningful - you will make an offset - so the string output will be rade 1: because "Grade 1" + 1 will point to the string literal rade 1).

cout << "Student Name: " << newStudent->name << endl;
cout << "Student ID: " << newStudent->id << endl;
cout << "Student Email: " << newStudent->email << endl;
cout << "Grade 1: " << newStudent->gradeOne << endl;
cout << "Grade 2: " << newStudent->gradeTwo << endl;
Nemanja Boric
  • 21,627
  • 6
  • 67
  • 91
-1

Your studentObj::gradeOne and studentObj::gradeTwo members are integer values. The string literal Grade 1: has type char*. An expression of type pointer + integer is the same as pointer[integer]. When you try to print the grade you are really producing a pointer into the string literal (if you are lucky).

IInspectable
  • 46,945
  • 8
  • 85
  • 181