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?
当我选择开关案例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]处的索引。
相关文章:
- 如何在linux终端中同时编译和运行c++代码
- 尝试用java代码编译和运行c++代码
- 不同/较旧的处理器运行c++代码的方式是否不同
- 无法在 geany 上运行代码。无法执行构建命令
- 运行代码时,c++ 会终止进程
- 编译多个C++文件.调用二进制文件以运行代码
- 分段故障 运行C++代码时出现 SIGSEGV
- 如何分析在 Windows 上运行C++代码?
- 编译器资源管理器(godbolt)如何安全地运行代码?
- 如何在 vim (windows) 中编译和运行 c++ 代码
- 无法在 Visual Studio 代码中生成和运行 C++ 代码
- 连续运行C++代码和 Python 代码
- 在静态初始化期间运行代码
- C++ .我正在尝试通过使用开关内的数组来获取用户输入,但是当我运行代码时,它显示分段错误?
- 我最近更改了编译器路径以运行 c++ 代码,但现在我无法运行任何 python 代码。我该如何解决这个问题?
- 如何在Visual Studio Code的终端内运行C++代码?
- 在注入的 Dll 的 DllMain 中运行代码导致注入超时
- 并行和顺序运行代码时会产生不同的结果
- 运行代码时C++错误
- 在 CortexM0 中从 RAM 运行代码时出现硬故障