単語がテキストファイルに表示される回数に単語をマッピングするテーブルを生成するプログラムを作成する必要があります。これまでのところ、私のコードは次のようになっています
#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.
1行あたりの正確な行数または単語数がわかりません。私が言っていたように、私の考えは、テキストファイルからすべての単語を取得して文字列の配列に入れ、配列内のすべての要素に対して挿入関数を実行することでした。各単語をどのように取得するかがわかりません。そしてそれを配列に入れます。どんな提案も歓迎し、感謝しています。
この使用法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の長さの単語を読み取り、関数を使用して各単語をテーブルに格納します。単語が正確に4KiBの長さであるか、それより長い場合、それは断片に分割されます。おそらく問題にはならないでしょう。scanf()
ファミリは、空白、タブ、および改行を単語間の区切り文字として扱うことに注意してください。"a-z"
ファイルへの書き込みは、1つの単語、二重引用符、ダッシュなどとして扱われます。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加