无法比较C中的char数组与指针的char数组

时间:2015-12-15 16:05:47

标签: c arrays pointers

我有一些单词存储在指针的char数组中,如

char* someWords[]={"a", "about", "above","across", "after", "afterwards",      
"again", "against", "all",
"almost", "alone", "along", "already","also","although","always","am","among"} //etc,320 words
char x[1024]; // used this to read file 

然后我读了另一个文件并取出这些单词以便与某些词进行比较,如果它们相同,我就不会计算它们。我做了类似的事情。

 while (fscanf(fone,"%1023s",x) == 1) { 
    i=0;


    while(i<541 && x!=someWords[i]){ //if file contains stopwords.  also tried (strcmp(x,someWords[i])!=0)

    i++;

    //printf("\n len:%d",strlen(x));

    }
    if(i==541)
    {
        printf("\n%s is not stop word ",x);   

    }
    else
    {
        printf("\n%s is stop word ",x);

    }
} 

问题是所有单词都打印为“不是停止词”,这使我发现程序无法比较xsomeWords[i]。那我该怎么做才能解决这个问题呢?我应该使用哪些类型的变量?或者我应该完全改变我的阅读文件的方法?

2 个答案:

答案 0 :(得分:3)

要比较两个字符串,请使用strcmp(x, someWords[i])。如果它们相等,结果将为0。

您无法与x!=someWords[i]进行比较,因为这只会比较指针,而不是字符串的内容。

答案 1 :(得分:2)

我已经修改了你的程序,它运行得很好。我有

  • 使用空指针终止了单词列表,这样我们就不会依赖数字。
  • 使用strcmp
  • stdin而不是从文件中读取(预期输入是一系列简单的单词,可能与也可能不匹配其中一个单词)。
  • 介绍&#34;发现&#34;标志和中间循环中断,而不是在循环条件中进行比较(这样我们可以做到的事情,如果找到的话)。

程序:

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

char* someWords[]=
    {   "a", "about", "above","across", 
        "after", "afterwards",      
        "almost", "alone", "along", 
        "already","also","although",
        "always","am","among", 0};      //etc,320 words

char x[1024]; // used this to read file 

int main()
{
    while (scanf("%1023s",x) == 1)
    {
        int found = 0;

        for(int i=0; someWords[i]; i++)
        {   printf("%s, %s\n",someWords[i], x);
            if( strcmp(x,someWords[i])==0 )
            {
                found = 1;
                break;
            }
        }       
        if(!found)
        {
            printf("\n%s is not stop word\n",x);   

        }
        else
        {
            printf("\n%s is stop word\n",x);

        }
    }   return 0;
}

示例会话:

$ gcc -std=c11 -Wall -o word-arr  word-arr.c  && ./word-arr 
above lalala <-- input 
a, above 
about, above 
above, above

above is stop word 
a, lalala 
about, lalala 
above, lalala 
across, lalala 
after, lalala 
afterwards, lalala 
almost, lalala 
alone, lalala 
along, lalala 
already, lalala 
also, lalala 
although, lalala 
always, lalala 
am, lalala 
among, lalala

lalala is not stop word