#include <stdio.h> #include <stdlib.h> #include <string.h> struct tch { char *name; int score; }; int main(int argc, char const *argv[]) { struct tch ths[4]; char *name = (char*)malloc(10*sizeof(char)); int score; int i = 0; int j = 0; for (j = 0; j < 4; ++j) { ths[j].name = (char*)malloc(10*sizeof(char)); ths[j].score= 0; } strcpy(ths[0].name,"fisher"); strcpy(ths[1].name,"lucas"); strcpy(ths[2].name,"urban"); strcpy(ths[3].name,"rural"); printf("comp:::\n%s\n%s\n%s\n%s\n", ths[0].name, ths[1].name, ths[2].name, ths[3].name );
//投票10次 输入姓名 while(i++<10) { j = 4; printf("stu%2d vote for:",i); scanf("%s",name); while(j--) { if(strcmp(name,ths[j].name) == 0) { ths[j].score++; break; } } } for(i = 0;i < 3 ; ++i) { for (j = i+1; j < 4 ; ++i) { if (ths[i].score < ths[j].score) { score = ths[i].score; ths[i].score = ths[j].score; ths[j].score = score; strcpy(name,ths[i].name); strcpy(ths[i].name,ths[j].name); strcpy(ths[j].name,name); } } } for (i = 0; i < 4; ++i) { printf("NO.%d is %10s with score %d\n",i+1,ths[i].name,ths[i].score ); free(ths[i].name); } free(name); return 0; }
调试运行没有报错,但是最后输入完以后,停止运行了
输入完就退出的意思吗?
你可以在return 0 前面加一个system("pause");
不是的 是这样的。。
@NoDense:
那么问题很有可能出现在这段代码里
1 for(i = 0;i < 3 ; ++i) 2 { 3 for (j = i+1; j < 4 ; ++i) 4 { 5 if (ths[i].score < ths[j].score) 6 { 7 score = ths[i].score; 8 ths[i].score = ths[j].score; 9 ths[j].score = score; 10 11 strcpy(name,ths[i].name); 12 strcpy(ths[i].name,ths[j].name); 13 strcpy(ths[j].name,name); 14 } 15 } 16 17 }
strcpy那个函数很容易出错,但问题更可能出现在上面的++i的地方(红色标注)。
i的作用域问题。
我怀疑那里应该是++j
@恋恋风尘Ming: 没问题了,谢谢,怪我自己眼花,检查不细致。。。没有注意到。。