[英]CS50 pset3 Plurality: why does vote function not return false when given invalid candidate?
According to check50, the vote function does not return false when given a name of an invalid candidate.根据 check50,投票 function 在给出无效候选人的姓名时不会返回 false。 Furthermore, it modifies total votes when voting for an invalid candidate.此外,它会在投票给无效候选人时修改总票数。 I left the main function unchanged, according to instructions.根据说明,我将主 function 保持不变。 Please help?请帮忙? What am I not seeing here?我在这里没有看到什么?
Edit: added the rest of the code.编辑:添加了代码的 rest。 When I run it with the example Alice and Bob as candidates and try to vote for Steve, instead of "Invalid vote" as the output should be, it gives me "Segmentation fault".当我以 Alice 和 Bob 作为候选人的示例运行它并尝试投票给 Steve 时,而不是 output 应该的“无效投票”,它给了我“分段错误”。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
// Max number of candidates
#define MAX 9
// Candidates have name and vote count
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1;
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2;
}
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
int voter_count = get_int("Number of voters: ");
// Loop over all voters
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name))
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner();
}
// Update vote totals given a new vote
bool vote(string name)
{
for (int i = 0; i < MAX; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
candidates[i].votes++;
return true;
}
}
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
int high = 0;
for (int i = 0; i < MAX; i++)
{
if (candidates[i].votes > high)
{
high = candidates[i].votes;
}
}
for (int j = 0; j < MAX; j++)
{
if (candidates[j].votes == high)
{
printf("%s\n", candidates[j].name);
}
}
return;
}
In vote and print_winner you loop on entire candidates array.在 vote 和 print_winner 中,你循环整个候选数组。
for (int i = 0; i < MAX; i++)
What do you think can happen when you fill only 2 candidates and try to access 3rd item of array which has not been initialized?当您仅填写 2 个候选人并尝试访问尚未初始化的数组的第 3 项时,您认为会发生什么? Usually, undefined behavior.通常,未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.