【发布时间】:2021-11-09 14:09:24
【问题描述】:
不知道我应该如何制定标题!
我正在尝试编写一个程序来询问用户学生的姓名。然后它将该名称存储在一个结构中,并要求提供课程名称和该课程的成绩。它会一直这样做,直到课程名称为 stop。然后它要求另一个学生,直到给出的名字是stop。
这是我的代码:
#include <iostream>
using namespace std;
struct student{
public:
string name;
string course;
int grade;
}student_t;
int main() {
while (student_t.name != "stop"){
cout << "Please type the name of a student: " << endl;
getline(cin, student_t.name);
if (student_t.name.compare("stop")){
break;
}
else{
if (student_t.course.compare("stop")){
break;
}
else {
cout << "Please type a course name: " << endl;
getline(cin, student_t.course);
cout << "Please type the grade: " << endl;
cin >> student_t.grade;
}
}
}
cout << student_t.name << " - " << student_t.course << " - " << student_t.grade << endl;
return 0;
}
问题是,无论我输入什么名称,它都会退出。
有什么想法吗?
【问题讨论】:
-
std::string::compare如果它们相等,则返回 0(在强制为 false 的 bool 表达式内),因此根据您的逻辑,如果您键入“stop”以外的任何内容,则将满足条件并且您将休息。 -
学习使用调试器。您可以逐行执行此程序并检查每个函数返回的值。您会注意到
student_t.name.compare("stop")返回了一些非零数字,即使名称不是"stop"。这应该是您更仔细地研究compare函数的线索。 -
谢谢大家! :)
标签: c++ for-loop struct while-loop