您的索引错误。
C和C++的利用
零标引
. 这意味着本机维度数组
N
可使用索引访问
0..(N-1)
. 你
student_position
当出现一个插入请求时,当它已经达到最大数组维数时,应该将明显的翻转标记回零。而且显示循环应该严格地从零到维度
小于
在顶端(因此符合
0..(N-1)
索引。
见下文:
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_STUDENT = 3;
struct student
{
char name[50];
char classID[15];
int age;
};
student student_list [MAX_STUDENT];
int student_position = 0;
void add_new(){
if (student_position == MAX_STUDENT) {
student_position = 0; // HERE
}
cout << "student name: " << endl;
cin >> student_list[student_position].name;
cout << "student classID: " << endl;
cin >> student_list[student_position].classID;
cout << "student age: " << endl;
cin >> student_list[student_position].age ;
++student_position; // HERE
}
void list(){
for(int i = 0; i < student_position; ++i){
cout << i << "/name: " << student_list[i].name << " - classID: " << student_list[i].classID << " - age: " << student_list[i].age << endl;
}
}
int main()
{
char command = 'a';
cout << "please input command: N (New), L (List), E (Exit), W(Write to file)." << endl;
while(cin >> command){
switch (command) {
case 'N':
add_new();
break;
case 'L':
list();
break;
case 'E':
return 0;
default:
cout << "wrong command" << endl;
break;
}
}
return 0;
}
这将解决故障问题,但留给您的任务是确定wrap逻辑是否正确。我想不是,但这不是问题所在。