【发布时间】:2021-10-11 01:25:47
【问题描述】:
我在这里有一个任务,过去几个小时我一直在做这个任务,但遇到了一个问题。每当我在 VS Code 中编译和运行程序时,它都会让我进入一个无限循环,其中重复打印“菜单”的文本。我想这与菜单开头的for(;;){ 循环有关。
我已经删除了菜单开头的for(;;){ 语句,并且连续滚动停止了,但是我无法输入任何数字(案例),并且程序本质上只是打印了菜单,这就是结束。
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class Student {
string name;
float GPA;
public:
string getName() const
{
return name;
}
float getGPA() const
{
return GPA;
}
void setName(string Name)
{
name = Name;
}
void setGPA(float gpa)
{
GPA = gpa;
}
Student(const string& name, float gpa)
: name(name)
, GPA(gpa)
{
}
Student()
{
}
void printDetails(Student s[], int n)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n; i++) {
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
float calcAverageGPA(Student s[], int n)
{
float avg = 0;
float sum = 0;
for (int i = 0; i <= n; i++) {
sum += s[i].getGPA();
}
avg = sum / n;
return avg;
}
float getGPAbyName(Student s[], int n, string name)
{
for (int i = 0; i <= n - 1; i++) {
if (s[i].getName() == name)
return s[i].getGPA();
}
return -1;
}
void showListByGPA(Student s[], int n, float gpa)
{
cout << setw(20) << "Name: " << setw(10) << "GPA: " << endl;
cout << "=========================================" << endl;
for (int i = 0; i < n - 1; i++) {
if (s[i].getGPA() > gpa)
;
cout << setw(20) << s[i].getName() << setw(10) << s[i].getGPA() << endl;
}
}
};
int main()
{
int n = 0;
int ch;
Student s[50];
string name;
float GPA;
float avg = 0;
cout << "======================" << endl;
cout << "(1): Add a student" << endl;
cout << "(2): Print the details of a student" << endl;
cout << "(3): Get the GPA of a Student by name." << endl;
cout << "(4): Get names of students based on GPA." << endl;
cout << "(6): Quit the program." << endl;
cout << "Enter your option" << endl;
switch (ch) {
case '1':
cout << "\nEnter student's name" << endl;
cin >> name;
cout << "Enter GPA" << endl;
cin >> GPA;
s[n] = Student(name, GPA);
n++;
break;
case '2':
s[0].printDetails(s, n);
break;
case '3':
cout << "\nEnter the name of a student" << endl;
cin >> name;
GPA = s[0].getGPAbyName(s, n, name);
if (GPA == -1) {
cout << "\nStudent not found!" << endl;
}
else
cout << "\nGPA is: " << endl;
break;
case '4':
cout << "\nEnter GPA: " << endl;
cin >> GPA;
s[0].showListByGPA(s, n, GPA);
break;
case '5':
avg = s[0].calcAverageGPA(s, n);
cout << "\nAverage GPA: " << avg << endl;
break;
case '6':
exit(0);
}
}
我怀疑问题出在main()。我包括了程序的前面部分,以防它们需要提供任何建议。
【问题讨论】:
-
'ch' 被定义为 int 但在 switch case 中,您直接检查字符 '1' 而不是 1。
-
在
main中,在为它分配值之前,您是参考ch。你没有收到警告? -
请使用 'cin' 语句获取 'ch' 的输入。因为我没有看到。
-
你在
ch哪里读到的? -
@jacob:我不使用 VSCode 但stackoverflow.com/questions/60872633/… 可能会有所帮助。
标签: c++