gpt4 book ai didi

C++。我试图通过在开关中使用数组来获取用户输入,但是当我运行代码时它显示段错误?

转载 作者:行者123 更新时间:2023-11-28 04:04:57 26 4
gpt4 key购买 nike

当我选择 switch case 1 并输入详细信息时,它正在向我展示!分段故障。我觉得这是因为数组输入。但是如何避免这种情况或者无论如何都可以解决这个问题?问题 - 基于上面的问题 1 和 2,修改程序使其显示菜单用户选择;添加新学生显示学生名单添加新类(class)显示类(class)提供用户可以选择安全退出/终止程序。问题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 List\n";

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 List\n";
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;

在 switch case 中,您正在更新 i=i+1,它试图访问 uniten[1] 中不存在的索引。

关于C++。我试图通过在开关中使用数组来获取用户输入,但是当我运行代码时它显示段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58897895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com