[英]CS50 Pset3 error: expected identifier or '('
我正在通过 CS50 执行 PSET3,但在编译代码时遇到问题。 它不断出现错误
plurality.c:44:21: error: expected identifier or '('
candidate[i].name = argv[i + 1];
这很奇怪,因为这是在我们开始问题之前给出的代码部分中。
我的完整代码在这里...
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.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++)
{
candidate[i].name = argv[i + 1];
candidate[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
// Local boolean variable
bool valid_vote = false;
// Iterating over number of candidates and comparing string "name" to get a boolean result.
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(name, candidate[i].name) == 0)
{
candidate[i].votes++;
valid_vote = true;
// Force a break in the program to exit with the correct result
break;
}
}
return valid_vote;
}
// Print the winner (or winners) of the election
void print_winner(void)
{
// Initialising a variable for the most votes, and the candidate
int highest_votes = candidates[0].votes;
string win = candidates[0].name;
// Looping through results and finding the highest "votes" value
for (int i = 0; i < candidate_count; i++)
{
if (candidate[i].votes > highest_votes)
{
highest_votes = candidate[i].votes;
win = candidate[i].name;
}
}
// Comparing all "votes" values and printing winner(s)
for (int j = 0; j < candidate_count; j++)
{
if (candidate[j].name == win)
{
printf("%s %s", win, candidates[j].name);
}
printf("%s", win);
}
return 0;
}
澄清一下,我不需要关于这个问题的帮助,只是具体的编译错误。
多谢你们
好的,这应该可以解决它。
您正在使用结构名称candidate
:
typedef struct
{
string name;
int votes;
} candidate;
// Array of candidates
candidate candidates[MAX];
但是在 for 循环中,您迭代了candidate
者而不是candidates
者:
所以改变这个:
for (int i = 0; i < candidate_count; i++)
{
candidate[i].name = argv[i + 1];
candidate[i].votes = 0;
}
对此:
for (int i = 0; i < candidate_count; i++)
{
candidates[i].name = argv[i + 1];
candidates[i].votes = 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.