【发布时间】:2014-10-30 18:03:46
【问题描述】:
我必须在 C 中做一个选举程序。
共有 7 名候选人和 365 票。我需要使用一组结构来做到这一点。我需要从文本文件中读取每个候选人的姓名和他们获得的票数。最后我需要输出选举的获胜者。
到目前为止,这是我的代码示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct candidates {
char name[20];
int votes;
};
int main()
{
//Counter
int i = 0;
int gVotes = 0;
//Votes counter
int v = 0;
//Sploit Vote
int spVote = 0;
struct candidates electionCandidate[7];
FILE *fp;
fp = fopen("elections.txt", "r");
for(i=0;i<7;i++)
{
char * aNames = fgets(electionCandidate[i].name, 20, fp);
}
//for testing each candidate gots their name
for(i=0;i<7;i++)
{
printf("%d. Candidate is %s\n\n", i+1, electionCandidate[i]);
}
//For 365 Votes
while (!feof(fp))
{
int iVoteFor = 0;
fscanf(fp, "%d", &iVoteFor);
electionCandidate[iVoteFor-1].votes++;
//gVotes is my counter for the number of entries.
printf("%d ", ++gVotes);
}
system("pause");
return 0;
}
//Ideas of what to use
这是我目前的选举.txt
Robert Bloom
John Brown
Michelle Dawn
Michael Hall
Sean O’Rielly
Arthur Smith
Carl White
3 3 81 1 2 3 1 2 4 5
1 6 12 9 6 5 0 2
8 46 6 8 3 2 8 0 12 6 1 8
3 11 7 5 5 8 9 10 12 1 3 12
2 23 2 5 7 4 11 8 6 11 12
9 11 7 9 3 1 2 10 12
12 7 11 9 6 6 0 1 10 7 11 2 8
0 12 8 10 11 2 2 8 4 2 12 3 2 9 1
4 88 7 7 4 12 2 10 10 9 4 12 9 3 12
0 48 0 6 5 9 0 5 3 11 6 0 3 0 1 2 3
4 1 1 2 3 3 3 3 3 3 3 3 3 3 8 4 5
9 1 2 12 1 7 7 7 7 7 7 7 7 7 7 7 4 7 1 2
4 5 1 2 3 1 2 8 7 12 95 41 1 7 5 4 4 4 4 4
4 4 4 4 4 4 4 4 4 1 1 1 1 6 6 6 6 6 7 7 7 7
7 8 8 9 9 8 7 7 1 1 2 3 5 4 4 6 8 7 52 1 4 7
5 2 5 4 7 7 7 7 7 7 7 4 7 7 7 1 2 5 4 7 8 7 4 1
4 7 8 7 4 1 5 2 5 2 3 6 5 3 2 1 2 1 2 3
2 2 5 1 4 7 7 7 7 7 7 7 7 7 7 7 7 1 2 1
3 4 5 1 2 3 1 2 3 1 4 5 8 1 2 4 1 4 2 5
6 7 8 1 2 3 3 4 7 7 7 7 7 7 7 8 1 2 3 4
编辑:
每位候选人获得 +1 票,选举候选人[0] 每获得一票,其余的以此类推。共有 365 名选民。
我能够从文本文件中输入每个候选人的姓名。现在的问题是将每张选票投给相应的候选人。此外,任何高于 7 的投票都是我试图在上面的代码中计算的被破坏的投票。代码编译但它崩溃了。
我正在使用 while(!feof) 但它似乎不起作用或者这不是正确的方法。任何建议。
编辑: 我正在使用调试器,发现它在一段时间内运行了几次(!feof) 但在其中一种情况下,它会给出错误并停止。
编辑: 通过注释掉这行代码electionCandidate[iVoteFor-1].votes++;程序一直读取到 365 值。
我如何分配给每个候选人投票?
【问题讨论】:
-
请不要使用
void main(),即使在支持它的Windows 上也是如此。正确的返回类型是int,在C89系统(比如微软的编译器)上,应该在main()的末尾加上return 0;。 -
您需要添加
FILE*btw的名称 -
1)
22在fgets(electionCandidate[i].name, 22, fp);当sizeof electionCandidate[i].name == 20时? 2)不要使用feof(),使用fscanf()的返回值。 3) 代码没有测试被破坏的选票。 -
代码对
while (!feof(fp)) { ...}做了一个很大的否定。fscanf()beforefeof()变为 true 未能读取任何选票,因此iVoteFor保持为 0。代码不进行范围检查,然后继续执行electionCandidate[0-1].votes++;之外的electionCandidate[]--> 哎呀。好奇:使用feof()建议参考什么? -
!feof 不会读取我正在读取的整个文件的内容吗?我在另一篇文章中看到了这个