【发布时间】:2021-01-11 17:00:58
【问题描述】:
任务是让人们在命令行中输入他们对候选人的投票,然后投票最多的候选人获胜。我只需要并且被允许为最后两个函数原型编写代码。
所以现在,多个代码可以正常工作...直到选民键入一个无效的名称,然后程序因“分段错误”而停止。我不明白究竟是什么原因造成的。我应该怎么做才能解决这个问题?
我有一个以前的代码版本,但不会发生这种情况。因此,当输入错误的名称时,它会按原样打印出“无效投票”。但是,即使这样也有没有提示的问题,所以如果有3个投票者,那么在3个提示后程序结束。如果每个人都正确输入,那很好。但是如果有一个无效的投票,那么程序在结束前只有两个有效的投票输入。
然后关于“打印获胜者”功能,CS50 中是否有任何功能可以让我选择最大的候选人[i].votes 还是必须以不同的方式解决...?
谢谢!
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// Max number of candidates
// "the MAX here is a constant (equal to 9) that you can use now"
#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)
{
// TODO
for (int h = 0; h < MAX; h++)
{
for (int i = 0; i < MAX; i++)
{
if (strcmp(candidates[i].name, name) == 0)
{
printf("Match\n");
candidates[i].votes++;
return true;
}
}
return false;
}
return 0;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
// TODO
printf("The winner is...");
return;
}
【问题讨论】:
-
候选数量存储在
candidate_count中。但是在vote()函数中,您正在检查直到MAX的每个候选人。结果,您将不存在的字符串指针传递给strcmp(),导致它访问未分配给您的程序的内存。
标签: c struct command-line command-prompt cs50