c - 从文件中的行读取最大单词时重复标记?

标签 c file

我需要从文件中读取一行,找到该行中最大的单词,然后读取下一个单词。看起来很简单。我是 C 的新手,所以我知道我可能遗漏了一些简单的东西。如果我不包含 '\n' 作为分隔符,它将打印文件中的空行(段落之间的行),如果最大的单词位于行尾,则将打印一个新行。如果我确实包含它,如果后面有一个空行,则 token 将重复,并且文件中的最后一行将被跳过。 这是代码:

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

#define BUFFSIZE 81

int main(int numParms, char *parms[])
{
    FILE *file;
    char buffer[BUFFSIZE];
    char *token;
    int lineNum = 0;
    int currSize = 0;


   file = fopen("in.txt" , "r");
   if(file == NULL) 
   {
        perror("Error opening file");
        return(-1);
   }
   fgets(buffer, BUFFSIZE, stdin);
   while(!feof(stdin)) 
   {    
        char bigWord[30];
        char currWord[30];
        int bigSize = 0;

        lineNum++;
        token = strtok(buffer, " \n\t");
        while(token != NULL)
        {               
            strcpy(currWord, token);
            currSize = strlen(currWord);
            if(currSize > bigSize && currSize != bigSize)
            {
                strcpy(bigWord, currWord);
                bigSize = strlen(bigWord);
            }
            token = strtok(NULL, " \n\t");  
        }
    printf("Line %d's word: %s\n", lineNum, bigWord);

    fgets(buffer, BUFFSIZE, stdin);
    }

   fclose(file);

   return(0);
}

最佳答案

  1. 未初始化的缓冲区。

    每当 fgets() 读取仅由 ' ''\n''\t 组成的行时', printf("... %s\n", ..., bigWord); 打印单位化的 bigWord,简单的可能有内容上一行解析。

  2. OP 打开文件,但使用stdin。 @BLUEPIXY

一些改进

// improved fgets() usage,  catches IO error, unlike before
while (fgets(buffer, BUFFSIZE, file) != NULL) {
  char bigWord[BUFFSIZE]; // Worst case size
  bigWord[0] = '\0';  // Initialize bigWord
  size_t bigSize = 0;  // type int is OK for small buffers, but size_t is best

  lineNum++;
  char *token = strtok(buffer, " \n\t"); // local declaration
  while(token != NULL) {               
    char currWord[BUFFSIZE]; // local declaration
    strcpy(currWord, token);
    size_t currSize = strlen(currWord);  // local declaration

    // Drop 2nd part of if() - not needed
    // if(currSize > bigSize && currSize != bigSize) {
    if(currSize > bigSize) {
      strcpy(bigWord, currWord);
      bigSize = strlen(bigWord);  // or just use bigSize = currSize
    }
    token = strtok(NULL, " \n\t");  
  }
  printf("Line %d's word: `%s`\n", lineNum, bigWord);  // added ``
}

其他可能的简化:
不需要 char currWord[BUFFSIZE],只需使用 token

关于c - 从文件中的行读取最大单词时重复标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26171235/

相关文章:

arrays - 如何在 C 编程中将 char 数组转换为 int 数组?

javascript - 在 javascript 中从我的 Parse 数据库中获取图像?

c++ - 使用函数和数组写入两个文件

C 正则表达式不匹配

c - 指针的作用类似于局部变量,并且不会在函数中保留其修改

linux - 是否有任何应用程序/编辑器可以跟踪文件中发生的更改并显示它们?

java - 文件未找到异常,相同目录存在

执行 File.Copy 时出现 C# unauthorizedAccessException

在c中创建带有链表的哈希表

c - C语言中i=1<<i是什么意思?