C++ .我正在尝试通过使用开关内的数组来获取用户输入,但是当我运行代码时,它显示分段错误?

c++ . I'm trying to get user input by using array inside switch but when i run the code it's showing segmentation fault?

本文关键字:运行 代码 输入 错误 分段 显示 用户 数组 C++ 开关 获取      更新时间:2023-10-16

当我选择开关案例1并输入详细信息时,它显示了我!分段故障。我觉得这是因为数组输入。但如何避免这种情况,或者是否有办法解决这个问题?问题-根据上面的问题1和2,修改程序,使其显示用户可以选择;添加新学生显示学生列表添加新课程提供的展示课程用户可以选择安全退出/终止程序。问题4根据上述问题1至3,修改程序,以便用户能够修改所选学生的姓名。

#include <iostream>
#include <string>
using namespace std;
struct  Student{
string name , id , nickname;

};
struct  Course{
string ccode,  cname, clecturer;

};

int main() {
int i=0, c=0, ti=0, tc=0;
Student uniten[i];
Course cuniten[c];
cout << "n n" << endl;

int choice;
bool gameOn = true;
while (gameOn != false){
cout << "*******************************n";
cout << " 1 - Add new students.n";
cout << " 2 - Display student list.n";
cout << " 3 - Add new course.n";
cout << " 4 - Display course offered.n";
cout << " 5 - Exit.n";
cout << " Enter your choice and press return: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Add new students.n";
i = i+1;
cout << "n n" << endl;
cout << "Student " << i << endl;
cout << "Enter Student ID: ";
cin >> (uniten[i].id);
cout << "Enter their Name: ";
cin >> uniten[i].name;
cout << "Enter their Nickname: ";
cin >> uniten[i].nickname;
cout << "n n" << endl;
break;
case 2:
cout << "Display Student Listn";
break;
case 3:
cout << "Add new course.n";
c = c+1;
cout << "n n" << endl;
cout << "Course " << c << endl;
cout << "Enter Course Code: ";
cin >> (cuniten[c].ccode);
cout << "Enter Course Name: ";
cin >> cuniten[c].cname;
cout << "Enter Lecturer Name: ";
cin >> cuniten[c].clecturer;

break;
case 4:
cout << "Display Course Listn";
for (tc=0; tc<c; tc++) {
cout << "Course : " << cuniten[i].cname << " Course Code : " << cuniten[i].ccode << ", Lecturer name : " << cuniten[i].clecturer <<endl;
cout << "n n" << endl;
}
break;
case 5:
cout << "End of Program.n";
gameOn = false;
break;
default:
cout << "Not a Valid Choice. n";
cout << "Choose again.n";
cin >> choice;
break;
}
}

}
int i=0, c=0, ti=0, tc=0;
Student uniten[i];
Course cuniten[c];

在上面的代码中,已经创建了大小分别为i=0和c=0的数组。

case 1:
cout << "Add new students.n";
i = i+1;
cout << "n n" << endl;
cout << "Student " << i << endl;
cout << "Enter Student ID: ";
cin >> (uniten[i].id);
cout << "Enter their Name: ";
cin >> uniten[i].name;
cout << "Enter their Nickname: ";
cin >> uniten[i].nickname;
cout << "n n" << endl;

在交换机的情况下,您正在更新i=i+1,它正试图访问不存在的uniten[1]处的索引。