Having code issue in C

旧时模样 提交于 2019-12-13 08:16:03

问题


Can anyone please tell me what is the problem with this code?

There is no issue in the compilation of this code but after compilation when I enter the data of Array of Objects of structure, the data is not entered after one loop.

#include<stdio.h>
struct process{
    char name;
    int arv;
    int burst;
}p[10];
int sort(struct process p[],int n){
    int i,j;
struct process t;
    for(i=0;i<n;i++){
        for(j=0;j<n-1-i;j++){
            if(p[j].arv>p[j+1].arv){
                p[j]=t;
                p[j]=p[j+1];
                p[j+1]=t;
            }
        }
    }
return 0;
}
int main(){
    int i,n;
    printf("Enter Number Of Processes");
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%c",&p[i].name);
        scanf("%d",&p[i].arv);
        scanf("%d",&p[i].burst);
    }
    sort(p,n);
    for(i=0;i<n;i++){
        printf("%c",p[i].name);
        printf("%d",p[i].arv);
        printf("%d",p[i].burst);
    }
return 0;
}

回答1:


Read documentation of scanf(3) and of fflush(3)

Always test the result of scanf

printf("Enter Number Of Processes");
fflush(NULL);
if (scanf("%d",&n)<1) 
 { perror("scanf nb process"); exit(EXIT_FAILURE); ; }

(do likewise for your other calls to scanf ...)

and at least call fflush at end of each for loop, e.g.

for(i=0;i<n;i++){
    printf("%c",p[i].name);
    printf("%d",p[i].arv);
    printf("%d",p[i].burst);
    fflush(NULL);
}

since stdio(3) is buffered. BTW, you'll be surprised by the output. You generally should end each (or at least most) printf format string with \n

BTW, you should compile with all warnings & debug info (gcc -Wall -Wextra -g) and you should use the debugger (gdb)




回答2:


I guess, you are facing problem with scanf(). But do not use fflush() as some of above answers suggest to use fflush(NULL) before scanf(). fflush() on input streams as stdin has undefined behaviour, Read Here fflush()

Instead use following to clear the stdin before every scanf.

while ((c = getchar()) != EOF && c != '\n') ;

It clears the newline character pressed after last input, which is not absorbed by scanf()

also check the return of scanf(), thats a good habit always.



来源:https://stackoverflow.com/questions/28007909/having-code-issue-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!