0

这是我目前的代码。现在我正在返回读取文本文件时出现的单词编号,我需要做的是返回该单词所在的行号,并将其打印在我返回到控制台的每个单词旁边。所以不是“你好世界”出现,你好 - 1 世界 -2,我需要 - 你好 -1 世界 -1

需要帮助弄清楚如何做到这一点。

#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <istream>
#include <conio.h>

    struct node
    {
        int key_value, lineNumber;
        char *word;
        struct node *left,*right;
    };

    struct node *inserttree(struct node *tree,char *s, int lineNumber)
    {
        int i;

      if (tree==NULL)
      {
        if ( ( tree = (struct node *) malloc( sizeof(struct node) ) ) !=NULL)
        {
          if ((tree->word=(char *) malloc(strlen(s)+1))==NULL)
          {
              free(tree);
              tree=NULL;
          }
          else
          {
              tree->left=NULL;
              tree->right=NULL;
              strcpy(tree->word,s);
                tree->lineNumber = lineNumber ;
          }
        }
      }

      else if ((i=strcmp(tree->word,s))>0)
      {
          tree->left=inserttree(tree->left,s, lineNumber);
      }
      else if (i<0)
      {
          tree->right=inserttree(tree->right,s, lineNumber);
      }

      return tree;
    }

    void printtree(struct node *tree)
    {

        if (tree!=NULL)
        {
            printtree(tree->left);
            printf("%s %d\n",tree->word, tree->lineNumber);

            printtree(tree->right);
        }
    }

    //int search(struct node *tree)
    //{
    //  int key;
    //  tree->right->key_value = key;
    //  return key;
    //}

    void freetree(struct node *tree)
    {
        if (tree!=NULL)
        {
            free(tree->word);
            freetree(tree->left);
            freetree(tree->right);
            free(tree);
        }
    }

    int main(void)
    {
        FILE *f;
        char s[1024]; /*assumes a word cannot be longer than 1023 chars*/
        struct node *tree=NULL;
        int line = 1;

    if ((f=fopen("Test.txt","r"))==NULL)
        printf("Unable to open Test.txt\n");
        else
        {
            while (fscanf(f,"%1023s",s)!=EOF)
            tree=inserttree(tree,s, line++);
            fclose(f);

            printtree(tree);  //moved from inserttree
            freetree(tree);
        }

    system("pause");
    return 0;
    }
4

1 回答 1

0

您可以向 printtree() 方法添加一个计数器变量,并将其设为 0 作为初始值:

int count = 0;
void printtree(struct node *tree, int count)
{

    if (tree!=NULL)
    {
        printtree(tree->left, ++count);

        printf("%s %d\n",tree->word, count-1);

        printtree(tree->right, count);
    }
}
于 2013-04-16T13:52:29.970 回答