#1
by ジーラ(初心者) » 6年前
英文を入力すると出てきた単語とその出現回数を表示するプログラムを、二分探索木を使って作っているのですが、どうも上手くいきません。
出力結果がどうしてこうなるのか、どこを直せばいいのか分かりません。
以前Linux環境でやったときは上手くいってたのですが……。データを移すのにドライブを経由したのが悪かったのでしょうか?
今やっているOSはWindows。コンパイラーはgccです。
コード:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char word[20];
int kaisu;
struct node *right;
struct node *left;
};
char tango[20];
struct node *insert(struct node *x,char *a)
{
if(x == NULL){
x=(struct node *)malloc(sizeof(struct node));
strcpy(x->word,a);
x->kaisu = 1;
x->left = NULL;
x->right = NULL;
}
else if(strcmp(a,x->word)==0)
x->kaisu += 1;
else if(strcmp(a,x->word)<0)
x->left =insert(x->left,a);
else
x->right =insert(x->right,a);
return x;
}
void treeprint(struct node *x)
{
if(x!=NULL){
treeprint(x->left);
printf("%s[%d]\n",x->word,x->kaisu);
treeprint(x->right);
}
}
char *GetWord(){
char a;
int len;
a=getchar();
while(a==' ' || a=='\n' || a=='.' || a=='.' || a=='\'' || a==','){
a=getchar();
len=0;
}
while(a!=' ' && a!='\n' && a!='.' && a!='.' && a!=','){
tango[len++]=a;
a=getchar();
}
tango[len]='\0';
return &tango[0];
}
int main(void)
{
struct node *root;
char *g;
root=NULL;
g=GetWord();
while(strcmp(g,"***END***")!=0){
root=insert(root,g);
g=GetWord();
}
treeprint(root);
return 0;
}
入力した英文は
コード:
This is a test file.
This file has two sentences.
***END***
そして結果が
コード:
[5]
This[1]
Thisfile[1]
Thisfilehas[1]
Thisfilehastwo[1]
Thisfilehastwosenten[1]
となってしまいます。
英文を入力すると出てきた単語とその出現回数を表示するプログラムを、二分探索木を使って作っているのですが、どうも上手くいきません。
出力結果がどうしてこうなるのか、どこを直せばいいのか分かりません。
以前Linux環境でやったときは上手くいってたのですが……。データを移すのにドライブを経由したのが悪かったのでしょうか?
今やっているOSはWindows。コンパイラーはgccです。
[code]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char word[20];
int kaisu;
struct node *right;
struct node *left;
};
char tango[20];
struct node *insert(struct node *x,char *a)
{
if(x == NULL){
x=(struct node *)malloc(sizeof(struct node));
strcpy(x->word,a);
x->kaisu = 1;
x->left = NULL;
x->right = NULL;
}
else if(strcmp(a,x->word)==0)
x->kaisu += 1;
else if(strcmp(a,x->word)<0)
x->left =insert(x->left,a);
else
x->right =insert(x->right,a);
return x;
}
void treeprint(struct node *x)
{
if(x!=NULL){
treeprint(x->left);
printf("%s[%d]\n",x->word,x->kaisu);
treeprint(x->right);
}
}
char *GetWord(){
char a;
int len;
a=getchar();
while(a==' ' || a=='\n' || a=='.' || a=='.' || a=='\'' || a==','){
a=getchar();
len=0;
}
while(a!=' ' && a!='\n' && a!='.' && a!='.' && a!=','){
tango[len++]=a;
a=getchar();
}
tango[len]='\0';
return &tango[0];
}
int main(void)
{
struct node *root;
char *g;
root=NULL;
g=GetWord();
while(strcmp(g,"***END***")!=0){
root=insert(root,g);
g=GetWord();
}
treeprint(root);
return 0;
}
[/code]
入力した英文は
[code]
This is a test file.
This file has two sentences.
***END***
[/code]
そして結果が
[code]
[5]
This[1]
Thisfile[1]
Thisfilehas[1]
Thisfilehastwo[1]
Thisfilehastwosenten[1]
[/code]
となってしまいます。