【发布时间】:2017-10-31 09:52:10
【问题描述】:
这是我的代码的一部分。当我运行我的代码时,它会请求用户输入,然后将其与记录在我的结构中的另一个整数匹配。当用户输入匹配时,它工作正常。但是当用户输入错误的输入时,就会出现分段错误。我应该在哪里修改我的代码?
long int userInput,endCheck; // Input from user
int flag=0; // check for match
int status;
int c; // controlling ctrl+D
int position= 999; // position of where the user input and data matched
LABEL:
printf("\n\t---------------------------------------\n");
printf("\n\nPlease enter the student ID which you want to find(3-times CTRL+D for finish):\n");
scanf("%d",&userInput);
if( (c=getchar()) == EOF){
exit(0);
}
for(i=0;i<lines,flag==0;i++){
if(index[i].id == userInput){
position=i;
flag=1;
}else{
position=999;
}
}
if(flag==0){
printf("id not found");
}
studentInfo info; // for storing the information which we will take between determined offsets
if(position!= 999){
if ( (pos = lseek(mainFile,index[position].offset , SEEK_SET)) == -1)/*going to determined offset and setting it as starting offset*/
{ perror("classlist"); return 4; }
while ( (ret= read(mainFile,&info, sizeof(info))) > 0 ){
printf("\n\nStudent ID: %d, Student Name: %s\n\n",info.id,info.name);
break;// to not take another students' informations.
}
}
flag=0;
goto LABEL;
printf("Program is terminated");
【问题讨论】:
-
什么是
index? -
哪一行有段错误?您指的“错误输入”是什么?你为什么使用goto?为什么要使用 GOTO?
-
索引是我的结构。在我的结构中,我有一个学生 ID,我正在尝试将其与用户的输入相匹配。
-
什么是导致段错误的输入,记录的信息是什么?
-
当您使用 gotos 提交格式不佳的代码时,请告诉我您的成绩。我真的很想知道你的老师有多好。
标签: c segmentation-fault