Strcmp不能比较来自argv的字符串

4

** 更新于 10 月 26 日 -> 首先感谢您所有的帮助,我现在离成功更近了,还需要更多的工作和学习,但我真的非常感激您的帮助 :-)

仍然不知道为什么 input.txt 文件中的第一个 "rain" 单词没有从 strcmp 中获得正面输出,而且从 cmd 中可以看到 "<" 符号除了最后一行以外都没有出现。

也检查了来自Removing trailing newline character from fgets() input 的突出响应

即使我更改代码如下:

while( fgets (line, sizeof line, fp)!=NULL ) {

  /* remove \n from at the end of the str buffer*/   
  char * pos;
  /*
  if ((pos = strchr(line, '\n')) != NULL)
     *pos = '\0';
  */
  line[strcspn(line, "\n")] = 0;

我得到的结果与使用if块的结果相同。也许我会得到额外的\ 0,这可能是情况。有没有链接可以让我了解刚才使用的分隔符,或一个不错的调试器参考资料等等……我会在这里找到后尽快查看。非常感谢您的帮助!
read5.c版本:现在从那个input.txt文件中,最后一个“rain”单词上有一个额外的空格,我删除了它并且能够以真实结果的形式找到和获取该最后一个单词,执行strcmp if语句块。但这是唯一一个从该if块中获得真正阳性结果的字符串。
在cmd上,我可以看到:
$./read5 input.txt rain output.txt sun
>Maria
>rain
>manel
>Bla bla
<rain>
Found it! rain

输出到 output.txt 文件中:

Maria
rain
manel
Bla bla
sun

read5.c

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

/**
* Compile program:
*    gcc read3.c -o read3
*
*/
int main (int argc, char **argv) {
   FILE *fp, *fo;
   char *compare, *replace;
   char line[246];

   if (argc <= 4){
      printf(">Missing arguments on the command line.\n");
      printf(">Be sure you run the program as\n\"./read3 input.txt compare outout.txt replace\"\n\n");
   }

   /* opening file for reading */
   fp = fopen(argv[1] , "r");
   if(fp == NULL){
      perror("Error opening input file");
      return 1;
   }
   compare = argv[2];

   fo = fopen(argv[3], "w");
   if(fo == NULL){
      perror("Error opening output file");
      return 1;  //TODO check if: return 1 because it was expected, right?
   }
   replace = argv[4];

   /*
   printf(); made to test version 2
   //printf("We are going to compare %s\n", compare);
   //printf("We are going to replace it with %s\n", replace);
   */


   while( fgets (line, sizeof line, fp)!=NULL ) {

      /* remove \n from at the end of the str buffer*/   
      char * pos;
      if ((pos = strchr(line, '\n')) != NULL)
         *pos = '\0';

      /* print str enclosed in <> so we can see what str actually contains */
      //printf("Inside the loop, got the string: %s\n", line);

      //printing the strings with defined delimiters
      printf("<%s>\n", line);

      if(strcmp(compare, line) == 0){
         printf("Found it! %s \n", line);
         fprintf(fo, "%s\n", replace);
      }
      else{
         fprintf(fo, "%s\n", line);
      }

   }
   fclose(fp);
   fclose(fo);

   return 0;
}

第一个无编辑的问题:25/10

我需要制作一个以这种方式运行的程序:

./read2 input.txt rain output.txt sun 

它读取input.txt,查找rain字符串,如果找到它就用sun字符串替换它,并将所有文本从input.txt输出到output.txt。但是,根据我目前的代码,strcmp没有比较我想要比较的字符串,也许是我在命令行上得到的额外空格,我不知道...现在做的事情是将input.txt中的所有内容复制到output.txt中... 它总是运行else块... Read2.c:
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
    FILE *fp, *fo;
    char str[60];

    //char* token;
    /* opening file for reading */
    fp = fopen(argv[1], "r");
    char *compare = argv[2];

    fo = fopen(argv[3], "w+");
    char *replace = argv[4];

    if (fp == NULL) {
        perror("Error opening file");
        return(-1);
    }

    //printf("We are going to compare %s\n", compare);

    //printf("We are going to replace it with %s\n", replace);

    while (fgets(str, 60, fp) != NULL) {
        /* writing content to stdout */
        //Take the \n out 
        //token = strtok(str, "\n");

        printf("Inside the loop, got the string: %s\n", str);
        if (strcmp(compare, str) == 0) {
            //puts(str);
            printf("Found it! %s \n", str);

            fprintf(fo, "%s", replace);
        } else {
            fprintf(fo, "%s", str);
        }
    }
    fclose(fp);

    return(0);
}

input.txt:

Maria
rain
manel
Bla bla
rain 

Ouput.txt变成了和input.txt完全一样的内容,而且在此之前它是空的,所以代码运行正常,只有测试strcmp的if块存在问题。


1
{btsdaf} - Jabberwocky
5
只有当输入文件中每行只有一个单词时,这种方法才有效。但是你忽略了 fgets 会保留输入字符串末尾的换行符。请参阅 fgets() 输入中删除尾随的换行符 - Weather Vane
1
{btsdaf} - M Oehm
2
{btsdaf} - Jabberwocky
2
{btsdaf} - M Oehm
显示剩余13条评论
3个回答

1

read.c

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

/**
* How to compile program:
*    gcc read.c -o read
*
* How to run the program: 
*      .> ./read input.txt rainy output.txt sunny
* (On Windows MinGW compiler, simply: 
*      .> read input.txt rainy output.txt sunny - without ./)
*
*/
int main (int argc, char **argv) {
   FILE *fp, *fo;
   char *compare, *replace;
   char line[246];

   if (argc <= 4){
      printf(">Missing arguments on the command line.\n");
      printf(">Be sure you run the program as\n\"./read input.txt compare outout.txt replace\"\n\n");
   }

   /* Opening files for reading */
   fp = fopen(argv[1] , "r");
   if(fp == NULL){
      perror("Error opening input file");
      return 1;
   }
   compare = argv[2];

   fo = fopen(argv[3], "w");
   if(fo == NULL){
      perror("Error opening output file");
      return 1; 
   }
   replace = argv[4];

   while( fgets (line, (sizeof line), fp)!=NULL ) {
      line[strcspn(line, "\n")] = 0;
       if(strcmp(compare, line) == 0){
         printf("Found it! %s \n", line);
         fprintf(fo, "%s\n", replace);
      }
      else{
         fprintf(fo, "%s\n", line);
      } 
   }
   fclose(fp);
   fclose(fo);
   return 0;
}

/* 
Important info

strcspn :: 
Locate first occurrence of character in string, 
after locating the first occurrence of \n, replaces it by 0.


Sources::
https://dev59.com/M3E85IYBdhLWcg3wnU0d#28462221

Used to debug:
.>printf("1st: Reads input.txt, removes '\\n' from fgets, and prints it \n");
.>printf("2nd: Compares each line with 'rainy' \n");


.>printf("<%s>\n", line);

*/

input.txt

cloudy
rainy
chilly
rainy
rainy

1
问题在于str缓冲区末尾的\nfgets会在读取行时在末尾添加\n,您需要在比较之前将其去除。
这就是您需要的内容:
  while (fgets(str, 60, fp) != NULL) {

    /* remove \n from at the end of the str buffer*/    
    char *pos;
    if ((pos = strchr(str, '\n')) != NULL)
      *pos = '\0';

    /* print str enclosed in <> so we can see what str actually contains */
    printf("Inside the loop, got the string: <%s>\n", str);

    if (strcmp(compare, str) == 0) {
      printf("Found it! %s\n", str);
      fprintf(fo, "%s\n", replace);
    }
    else {
      fprintf(fo, "%s\n", str);
    }
  }

请查看代码中的注释以获取解释。


0

你的方法失败了,因为从输入文件中读取的行包含一个尾随的换行符'\n',这使得比较返回非零值。

在与搜索字符串进行比较之前,你可以去掉换行符。

请注意还有其他问题:

  • 你应该通过测试argc > 4来验证是否传递了足够的命令行参数。
  • 没有必要以更新模式"w+"打开输出文件,"w"更简单、更好。
  • 60个字节对于行数组来说有点小,限制了正确处理的最长行为58个字节。

这是一个改进版:

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

int main(int argc, char **argv) {
    FILE *fp, *fo;
    char *compare, *replace;
    char line[256];

    if (argc <= 4) {
        printf("missing command line arguments\n");
        return 1;
    }
    fp = fopen(argv[1], "r");
    if (fp == NULL) {
        perror("Error opening input file");
        return 1;
    }
    compare = argv[2];
    fo = fopen(argv[3], "w");
    if (fo == NULL) {
        perror("Error opening output file");
        return 1;
    }
    replace = argv[4];

    while (fgets(line, sizeof line, fp) != NULL) {
        line[strcspn(line, "\n")] = '\0';
        if (strcmp(line, compare) == 0) {
            printf("fount it!);
            fprintf(fo, "%s\n", replace);
        } else {
            fprintf(fo, "%s\n", line);
        }
    }
    fclose(fp);
    fclose(fo);

    return 0;
}

请注意,长行将被分成适合于“line”数组的块,因此上述天真方法可能会产生误报。
您可以使用以下内部循环完全消除此限制:
int c;
int pos = 0;
int cmplen = strlen(compare);
for (;;) {
    c = getc(fp);
    if (c == '\n' || c == EOF) {
        if (pos == cmplen) {
            fprintf(fo, "%s", replace);
        } else
        if (pos > 0) {
            fprintf(fo, "%*s", pos, compare);
        }
        pos = 0;
        if (c == EOF)
            break;
    } else {
        if (pos >= 0) {
            if (compare[pos] == (char)c) {
                pos++;
                continue;
            }
            if (pos > 0) {
                fprintf(fo, "%*s", pos, compare);
            }
            pos = -1;
        }
    }
    putc(c, fo);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接