在C中有代码问题 [英] Having code issue in C
问题描述
任何人都可以告诉我这个代码的问题是什么?
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;
}
推荐答案
=http://man7.org/linux/man-pages/man3/scanf.3.html =nofollow> scanf(3)和 fflush(3)
Read documentation of scanf(3) and of fflush(3)
始终测试结果 scanf
printf("Enter Number Of Processes");
fflush(NULL);
if (scanf("%d",&n)<1)
{ perror("scanf nb process"); exit(EXIT_FAILURE); ; }
(对于 scanf
...)
,并在每个结尾处至少调用 fflush
for
循环,例如
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);
}
因为 stdio(3)是缓冲的。 BTW,你会惊讶的输出。您通常应该使用 \\\
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,你应该编译所有警告&调试信息( gcc -Wall -Wextra -g
),你应该使用调试器( gdb
)
BTW, you should compile with all warnings & debug info (gcc -Wall -Wextra -g
) and you should use the debugger (gdb
)
这篇关于在C中有代码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!