首页 新闻 会员 周边

【问题】写了一个投票系统,投完票就停止运行了。。

0
悬赏园豆:5 [已解决问题] 解决于 2017-05-15 20:39
#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; }

调试运行没有报错,但是最后输入完以后,停止运行了

NoDense的主页 NoDense | 初学一级 | 园豆:199
提问于:2017-05-14 23:10
< >
分享
最佳答案
1

输入完就退出的意思吗?

你可以在return 0 前面加一个system("pause");

收获园豆:5
去冰三分糖 | 菜鸟二级 |园豆:380 | 2017-05-15 10:01

不是的  是这样的。。

NoDense | 园豆:199 (初学一级) | 2017-05-15 18:17

@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

去冰三分糖 | 园豆:380 (菜鸟二级) | 2017-05-15 19:19

@恋恋风尘Ming: 没问题了,谢谢,怪我自己眼花,检查不细致。。。没有注意到。。

NoDense | 园豆:199 (初学一级) | 2017-05-15 20:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册