【问题标题】:C Beginner: How to search for particular words in a file (line by line) in CC初学者:如何在C中搜索文件中的特定单词(逐行)
【发布时间】:2012-05-01 15:47:20
【问题描述】:

我需要逐行搜索文件中的两个特定单词,如果它们存在,则打印“找到!”。

这是file.txt(有四列)

bill gates 62bill microsoft 
beyonce knowles 300mill entertainment 
my name -$9000 student

以下是我的想法,但它似乎不起作用

char firstname[];
char lastname[];
char string_0[256];

file = fopen("file.txt","r+");

while((fgets(string_0,256,file)) != NULL) {

  //scans the line then sets 1st and 2nd word to those variables
  fscanf(file,"%s %s",&firstname, &lastname);

  if(strcmp(firstname,"beyonce")==0 && strcmp(lastname,"knowles")==0){
    printf("A match has been found");
  }
}

fclose(file);

请帮忙。可能是指针没有移动到while循环中的下一行吗?如果是这样,我该如何解决?

【问题讨论】:

  • 你在用string_0做什么,用sscanf(string_9,"%s %s,&firstname,&lastname)
  • 现在我发现我什么都没做。汤姆·迪格南帮助了我。谢谢

标签: c file while-loop strcmp


【解决方案1】:

在您已经使用 fgets 读取 file 之后,不应在 file 上调用 fscanf,而应在 string_0 变量上调用 sscanf,将数据复制到您的 @ 987654326@电话。

【讨论】:

    【解决方案2】:

    一种方法是使用fget 函数并在文本中查找子字符串。试试这样的:

    int main(int argc, char **argv)
    {
        FILE *fp=fopen(argv[1],"r");
        char tmp[256]={0x0};
        while(fp && fget(tmp, sizeof(tmp), fp))
        {
            if (strstr(tmp, "word1"))
                printf("%s", tmp);
            else if (strstr(tmp, "word2"))
                printf("%s", tmp);
        }
        if(fp) fclose(fp);
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      相关资源
      最近更新 更多