C-如何将文本文件中的单词读入字符串数组

时间:2015-03-31 00:26:23

标签: c arrays

我需要编写一个程序,生成一个表格,将单词映射到单词出现在文本文件中的次数。到目前为止,我的代码看起来像这样

#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
struct entry
{
  char* word;
  unsigned int n;
  struct entry *left;
  struct entry *right;
};

struct entry* 
insert(struct entry *table, char *str)
{
  if(table==NULL){
    table = (struct entry*)malloc(sizeof(struct entry));
    table->word = str;
    table->n = 1;
    table->left = NULL;
    table->right = NULL;
  }else if(strcmp(table->word,str)==0){
    table->n=(table->n)+1;
  }else if(strcmp(table->word,str)==1){
    table->left=insert(table->left,str);
  }else{
    table->right = insert(table->right,str);
  }
  return table;
}

void
print_table(struct entry *table)
{
  if(!(table==NULL)){
    print_table(table->left);
    fprintf(stdout,"%s\t %d\n",table->word,table->n);
    print_table(table->right);
  }
}

int
main(int argc, const char *argv[])
{

  struct entry* table = NULL;
  char *str = "foo";
  table =  insert(table,str);
  str = "foo";
  table = insert(table,str); 
  print_table(table);

  return 0;

}

给出了

的输出
foo 2

我需要做的是用输入文件做这件事。我的想法是把文本文件的每一个字看起来像

This is an example of 
what the text file
will look like.

我不知道每行的确切行数或单词数是多少。正如我所说,我的想法是从文本文件中取出每一个字并将其放入一个字符串数组中,然后通过数组中的每个元素运行我的插入函数,我只是不知道我应该如何去获取每个单词并将其放入数组中。任何建议都欢迎和赞赏。

2 个答案:

答案 0 :(得分:2)

如果您想存储以下段落中的每个单词

This is an example of 
what the text file
will look like.

以下内容可行:

while(true){
    while(inFile >> yourword){
    //store yourword here
    }
    getline(inFile, yourword); //discards the newline
    if(/*some_conditional_to_break*/)
    break;
}

答案 1 :(得分:0)

可移植性错误

请注意,使用strcmp()是错误的:

}else if(strcmp(table->word,str)==1){

strcmp()的定义是它返回一个小于零,等于零或大于零的值。没有提到1

始终,但始终与0比较:

  • if (strcmp(word, str) == 0) - word等于str
  • if (strcmp(word, str) != 0) - word不等于str
  • if (strcmp(word, str) <= 0) - word小于或等于str
  • if (strcmp(word, str) >= 0) - word大于或等于str
  • if (strcmp(word, str) < 0) - word小于str
  • if (strcmp(word, str) > 0) - word大于str

在许多实现中,strcmp()的返回值是不同字符之间的数字差异,可以大于或小于1.

读字

如果你有理由相信你的输入不会完全疯狂,你可以在这个循环中使用一个变体来读取数据:

char buffer[4096];
while (fscanf(fp, "%4095s", buffer) == 1)
{
    char *word = strdup(buffer);
    table = insert(table, word);
}

这会读取长达4 KiB的单词,并使用您的函数将每个单词存储在您的表中。如果一个单词的长度恰好是4 KiB或更长,它将被分成几部分。这可能不是问题。请注意,scanf()系列将空格,制表符和换行符视为单词之间的分隔符。在文件中编写"a-z"被视为一个单词,双引号,破折号和全部。

相关问题