【问题标题】:strcmp() not comparingstrcmp() 不比较
【发布时间】:2012-05-24 21:35:34
【问题描述】:

大家好, 我是一个新手,我正在编写一个代码,主要目的是在两个字符串相等时打印一个数字。第一个字符串是从文件中获取的,第二个是要比较的字符串。

代码:

int main()
{
char *string[2];
FILE *stream;
stream = fopen("REL","r");
if( (stream = fopen("REL","r")) == NULL)
{  
    printf("Can't open %s\n","REL");
    exit(1);
}
for(int i=0;i<92;i++)
{
    fscanf(stream,"%s",&string);
    if( strcmp("20", *string) == 0 )
    {
        printf("%d",20);
    }
}
fclose(stream);
}

并且...当我在 shell 上测试时,它提示我:

~/CM$ ./file2 
Segmentation fault (core dumped)

我可能犯了一个愚蠢的错误。但是,作为一个新手,我无法弄清楚脚本出了什么问题。

【问题讨论】:

    标签: c string compare strcmp


    【解决方案1】:

    string 是 2 个 char* 的统一数组。 fscanf 正在尝试写入不应写入的内存。将string 声明为一个字符数组:

    char string[256];
    

    和:

    fscanf(stream, "%255s", string); /* Limit number of
                                        chars read to prevent buffer overrun. */
    

    【讨论】:

      【解决方案2】:

      试试这个:

      char string[128];
      fscanf(stream, "%s", string);
      

      然后:

      if (!strcmp("20", string)) {
          /* The strings are equals */
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多