为什么c编译器在我的if语句中跳过strcmp()?

问题描述 投票:-3回答:1

我的函数投票必须检查在name中传递的字符串是否等于candidates[k].name中的任何一个,然后相应地更新投票。我正在用C编写代码它总是看起来总是返回false,并且在调试时,由于某种原因,我的编译器由于某些原因而停止在if语句中执行,而且我不知道为什么需要帮助这是相关的代码:

#define MAX_VOTERS 100
#define MAX_CANDIDATES 9

// preferences[i][j] is jth preference for voter i
int preferences[MAX_VOTERS][MAX_CANDIDATES];

// Candidates have name, vote count, eliminated status
typedef struct
    {
    string name;
    int votes;
    bool eliminated;
}
candidate;

// Array of candidates
candidate candidates[MAX_CANDIDATES];

// Numbers of voters and candidates
int voter_count;
int candidate_count;

// Function prototypes
bool vote(int voter, int rank, string name);
void tabulate(void);
bool print_winner(void);
int find_min(void);
bool is_tie(int min);
void eliminate(int min);

    bool vote(int voter, int rank, string name)
    {
        // TODO
        bool flag = false;
        for (int k = 0 ; k < candidate_count ; k++)
        {
            if(strcmp(name,candidates[k].name) == 0)
           { 
               preferences[voter][rank] = k;
               flag = true;
            }
            else
            {
                flag = false;
            }
        }
            return flag;

    }
c string strcmp
1个回答
-2
投票

对于C ++ std :: string,请使用string :: compare进行比较,或使用==<>之类的运算符。

strcmp()将c字符串(char数组)作为参数。但是,您似乎正在将字符串传递给该函数。最好在C ++中将上述方法用于std :: string比较。

如果要对字符串使用strcmp(),则可以按如下方式使用c_str()->>

if(strcmp(name.c_str(),candidates[k].name)
    
© www.soinside.com 2019 - 2024. All rights reserved.