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

标签 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.

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

最佳答案

如果要存储下一段的每一个单词

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;
}

关于C-如何将文本文件中的单词读入字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29358595/

相关文章:

c - 在 C 中模拟按键

c - 读取MP3 IDV2标签大小

java - 数组不会通过 for 循环到达下一个位置

c - 如何正确清除结构数组

c - 指向指针不准确的指针

javascript - Protractor - 比较 2 个数组的差异

在 C 中将客户端的字符串十六进制消息转换为服务器上的整数

c - 难以理解循环

c - 阻塞读取直到指定数量的字节到达

java - 获取在 ListActivity 中单击的项目的信息?