c++ - 读取不同的输入类型 C++

标签 c++ cin

我正在尝试创建一个学生对象,该对象采用姓名、ID、电子邮件和三个整数等级。

我的代码很简单,如下:

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');在一些地方,但没有运气。有什么建议么? `

最佳答案

您不能将字符串文字添加到整数(好吧,您可以,但在您的情况下您不会得到任何有意义的东西 - 您将进行偏移 - 因此字符串输出将是 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;

关于c++ - 读取不同的输入类型 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18774983/

相关文章:

c++ - 预处理器错误 C++

c++ - 当从 GCC 3.1.2 移植到 4.2.2 时编码中断

c++ - 断言失败 2 个不同的错误

c++ - 当 cin 的输入是 'dot' 时 while 循环到无穷大

c++ - cin 对象 - C++

c++ - cin,输入所需详细信息后无输出

c++ - 永远不会在 gmock 中调用 C 字符串

c++ - 为什么 C++ 编译器允许 extern 关键字与定义相结合?

C++ getline inside while loop 缺少第一个字母。没有 cin.ignore 不工作?

c++ - 将输入读入 vector 对象