【问题标题】:program to find individual word count in a para查找段落中单个字数的程序
【发布时间】:2011-06-19 10:44:08
【问题描述】:

这是一个程序,用于计算变量para中的单个字数作为输入。

我尝试过使用链表。

这里的变量complete 是一个像哈希码一样存储所有字母的数组,我根据哈希链接新单词,如果有相同的单词,那么我正在增加计数。这是我遵循的逻辑。

但事情是在程序中,它没有进入为重复单词而编写的代码的特定部分,也没有增加计数。

这是我的代码,任何人都可以帮助我。

#include<stdio.h> 
#include<conio.h>
#include<string.h>
#define NULL 0
struct wordcount 
{
char *s;
int count;
struct wordcount *next;
};
struct checkletter
{
char alph;
struct wordcount *next;
};
struct wordcount * create(char *);
main()
{
char *c,*s1,*intm;
char hastlet;
int hash[26],len,i,k=0,r,j,m=0,t,flag=0;
struct checkletter complete[26];
struct wordcount *node;
clrscr();
for(r=0;r<=25;r++)
{   complete[r].alph=r+97;
    complete[r].next=NULL;
}
for(r=0;r<=25;r++)
{
    printf("%c",complete[r].alph);
}
printf("\n");
printf("Enter the para :");
gets(c);
len=strlen(c);
    //arranging the words and putting them with count
for(i=0;i<len;i++)
{       k=0;
    intm='\0';
    if(c[i]==' ')
    {       for(j=m;j<i;j++)
        {
            intm[k]=c[j];
            k++;

        }
        intm[k]='\0';
        strcpy(s1,intm);
        m=k;
        m++;

        hastlet=s1[0];

        for(t=0;t<26;t++)
        {
            if(complete[t].alph==hastlet)
            {      
                node=complete[t].next;
                if(node==NULL)
                {      
                    complete[t].next=create(s1);
                    node=complete[t].next;
                    break;
                }
                else
                {   while(!strcmp(node->s,s1))
                    {
                        node=node->next;
                        if(node->next==NULL)
                        {   flag++;
                            break;
                        }
                    }

                    if(!strcmp(node->s,s1))
                        (node->count)+=1;
                    if(flag)
                    {   node->next=create(s1);
                    }
                }       break;
            }
        }


    }
}

//displaying the word that are counted

for(i=0;i<26;i++)
{   node=complete[i].next;
if(complete[i].next!=NULL)
while(1)
{   printf("%s---%d",node->s,node->count);
    if(node->next==NULL)
        break;

}
}



getch();
}

struct wordcount * create(char *y)
{
struct wordcount *newnode;
newnode->s=y;
newnode->count=0;
newnode->next=NULL;
return newnode;
}

【问题讨论】:

    标签: c string pointers memory-management data-structures


    【解决方案1】:

    以下不正确:

    char *c;
    ...
    gets(c);
    

    在gets 函数中使用未初始化的指针c 会导致未定义的行为。您需要为c 分配内存,这比您希望存储的最大字符数大一。

    intm 也是如此。

    另外,使用fgets 代替gets

    【讨论】:

    • 当我给这个程序(输入:hello hello hello)第一次迭代时,“h”哈希码链接将为空。并且一个词将被链接。对我来说,问题是当它进行第二次迭代时,它正在考虑好像“h”哈希码链接为空......我能知道它为什么吗?
    猜你喜欢
    • 2020-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    相关资源
    最近更新 更多