【问题标题】:Comparing chars[] does not work比较 chars[] 不起作用
【发布时间】:2013-12-26 08:00:35
【问题描述】:

我对 strcmp 函数有疑问(同样的问题是 here,但没有好的答案)。如果我比较 2 个相同的字符串,但一个字符串来自结构,则该字符串被错误地“翻译”为汇编代码。结构中的每个 char[] 都是随机的 3 个字符。 Picture of strcmp.asm

#define CONS 60

typedef struct LinkCity{
    char city[CONS];           // i get this char[] from file by using fgets()
    struct LinkCity* next;
} tLinkCity;
/***************************************/
    typedef struct {
        int NumberOfCity;
        tLinkCity* Link;
        double** distances;
    } tDatabaze;
/***************************************/
int GetIndexOfCity(tDatabaze* db, char * city){

    printf("%s %s", db->Link->city, city); //   > Barcelona\n Barcelona (yes, here is a newline)
    str = strcmp(db->Link->city, city);    //   str = 1  (=it should be 0)
}

【问题讨论】:

  • 当您使用fgets() 检索字符串时,您是否还记得从末尾删除换行符? tSeznamMest 是什么,db->Link 甚至分配在哪里?发布一个重现问题的真实示例。
  • 这和组装有什么关系?
  • 抱歉 tSeznamMest,已编辑...
  • 字符串中可能有非打印字符。 strlen() 对这两个字符串说什么?
  • 如果您的问题是关于您自己的 asm 函数,您应该发布它,而不是 C 代码。

标签: c strcmp


【解决方案1】:

在比较之前尝试从字符串末尾删除换行符,这是一个简单的函数:

void removeNLine(char* string)
{
        int i ;
        for(i = strlen(string) ; i > 0 ; i--)
               if(string[i] == '\n')
                     string[i] = '\0';
}

【讨论】:

    【解决方案2】:

    如果我没记错的话,函数fgets 也会将换行符读入数组。所以我认为两个数组不相等的原因是使用fgets读取的数组包含换行符。

    【讨论】:

    • 换行符将由printf() 打印,不是吗?
    • 我知道,但我尝试复制(使用 strcpy()),这也不起作用。
    • @Barma,是的,它可以帮助确定是否确实存在换行符。
    • @Pivoman 目前尚不清楚您要复制什么以及有什么问题。
    • @VladfromMoscow 那他为什么没有在他的 printf 中看到换行符?
    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多