首页 > 解决方案 > CS50 复数编译失败

问题描述

我总是在我的本地计算机上处​​理 Psets 并替换string为,char *因此我不必在我的头文件中使用 CS50 库。这是我对为什么我的代码在运行时无法编译的唯一解释check50

该代码在我的机器和 CS50 IDE 上都按预期工作,但check50仍然给我这个错误:

code failed to compile
Log
running clang plurality.c -o plurality -std=c11 -ggdb -lm -lcs50...
running clang plurality_test.c -o plurality_test -std=c11 -ggdb -lm -lcs50...
plurality_test.c:68:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
plurality_test.c:109:20: error: unknown type name 'string'
int main(int argc, string argv[])
^
1 warning and 1 error generated.

复数.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    char *name;
    int votes;
} candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(char name[]);
void print_winner(void);
int search(char name[]);

int main(int argc, char *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;
    printf("Number of voters: ");
    scanf("%i", &voter_count);

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        char name[10];
        printf("Vote: ");
        scanf("%s", name);

        // 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(char name[])
{
    for (int i = 0; i < candidate_count; 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 prev = -1;
    int curr;
    int id;

    for (int i = 0; i < candidate_count + 1; i++)
    {
        curr = candidates[i].votes;

        if (curr > prev)
        {
            id = i;
            prev = candidates[id].votes;
        }
    }

    printf("%s\n", candidates[id].name);
    return;
}

标签: cstringcs50

解决方案


@Blauelf 回答了这个问题:

检查器代码重命名您的main函数并附加自己的函数。

存在警告是因为如果您不显式返回值(默认情况下它将返回 0),则返回值仍然定义main的唯一函数是返回非的函数。void对于其他函数,返回值是多少取决于编译器,通常取决于 CPU 架构。通过重命名函数,此特殊属性不再适用。没问题,因为它只是一个警告,并且永远不会调用该函数。

然后他们附加自己的main函数,这就是错误发生的地方:那个人希望你#include <cs50.h>. 确保为提交添加此行,即使您自己不使用它的功能。


推荐阅读