c ++。我试图通过在switch内使用数组来获取用户输入,但是当我运行代码时,它显示了分段错误?

问题描述 投票:0回答:1

当我选择开关盒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 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;
}

}


}
c++ arrays input switch-statement
1个回答
0
投票
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]处的索引。

© www.soinside.com 2019 - 2024. All rights reserved.