0

我正在尝试创建一个学生对象,它采用姓名、身份证、电子邮件和三个整数成绩。

我的代码很简单,如下所示:

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;

我以为这会完美运行,但不幸的是事实并非如此。getline()混合和似乎是一个问题cin

输出是:

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

我试过cin.ignore(numeric_limits<streamsize>::max(),'\n');在几个地方添加,但没有运气。有什么建议么?`

4

2 回答 2

3

您不能将字符串文字添加到整数(好吧,您可以,但在您的情况下,您不会得到任何有意义的东西 - 您将进行偏移 - 所以字符串输出将是rade 1:因为"Grade 1" + 1将指向字符串文字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;
于 2013-09-12T22:03:24.513 回答
-1

您的studentObj::gradeOnestudentObj::gradeTwo成员是整数值。字符串文字Grade 1:的类型为char*。类型的表达式pointer + integer与 相同pointer[integer]。当您尝试打印成绩时,您实际上是在生成指向字符串文字的指针(如果幸运的话)。

于 2013-09-12T22:05:40.677 回答