473,785 Members | 2,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ File input...and delimiters

3 New Member
Ok, I feel like such an idiot with C++...gimme C# or Java any day of the week.

I have a tree program that (works) creates a tree, inorder traverses it, and then prints out messages before deleting the tree (and printing out more messages). That all works.

What doesn't work is the interface from the file to the tree. Uh, let me explain that. When I started this program, I just asked the user to input the tree from the console, easy peasy, right? Well, I actually need to take the data from a file that looks like this...

{ ROOT } //this is one tree
{ ROOT { FRED } } //this is one tree
{ ROOT { FRED { FRED_JUNIOR1 } { FRED_JUNIOR2} } }//this is one tree
{ ROOT
{ FRED
{ FRED_JUNIOR1}
{ FRED_JUNIOR2}
}
{ BARNEY
{ BARNEY_JUNIOR1}
{ BARNEY_JUNIOR2}
}
}// and this is the final tree

Since C++ is uhhh primative, I can't just use a file delimiter and a string tokenizer to strip out the whitespace and add to the tree properly.

My question is simple, how do I take a line and add just the word to the tree while using the open and closed brackets to indicate whether or not it is a new tree?

Here is my code...

Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string> 
  4.  
  5. using namespace std;
  6.  
  7. struct tree_node
  8.  {
  9.   char string[100];
  10.   tree_node *left;
  11.   tree_node *right;
  12.  };
  13.  
  14. tree_node *root;
  15.  
  16. void add_to_tree(char string[100]);
  17. void attach_node(tree_node *new_node_ptr);
  18.  
  19. void pre_order(tree_node *current_node);
  20.  
  21. void dispose_of_tree(tree_node *current_node);
  22.  
  23. int main()
  24. {
  25.  
  26.  
  27.     root = NULL; // initialize root of tree to NULL
  28.  
  29.     string line;
  30.      char string[100];
  31.      int length;
  32.     int oCount = 0;
  33.  
  34.     bool flag = true;
  35.      int target, target1, target2;
  36.     ifstream textFile ("tree.txt");
  37.      if (textFile.is_open())
  38.          {
  39.             while (! textFile.eof())
  40.                 {
  41.                     getline (textFile, line);
  42.                     for (int x = 0; x < line.length(); x++)
  43.                     {
  44.                         if (line.substr(x) == "R")
  45.                         {
  46.                         cout << line.substr(x) << endl;       
  47.                              }     
  48.  
  49.  
  50.                     }//close for
  51.  
  52.  
  53.                 }//close top while
  54.             } //close if 
  55.  
  56.     pre_order(root);
  57.     dispose_of_tree(root);
  58.     textFile.close();
  59.  
  60.     return 0;
  61. }
  62.  
  63.  
  64.  
  65. void add_to_tree(char string[20])
  66. {
  67.  tree_node *new_node_ptr;
  68.  
  69.  new_node_ptr = new tree_node;
  70.  
  71.  // Initialize new node.
  72.  strcpy(new_node_ptr->string, string);
  73.  new_node_ptr->left = NULL;
  74.  new_node_ptr->right = NULL;
  75.  
  76.  if(root == NULL)
  77.   {
  78.    root = new_node_ptr;
  79.   }
  80.  else
  81.   {
  82.    attach_node(new_node_ptr);
  83.   }
  84. }
  85.  
  86. void attach_node(tree_node *new_node_ptr)
  87. {
  88.  tree_node *search_ptr;
  89.  tree_node *follow_ptr;
  90.  
  91.  search_ptr = root;
  92.  follow_ptr = root;
  93.  
  94.  while(search_ptr != NULL)
  95.   {
  96.    follow_ptr = search_ptr;
  97.    if(strcmp(new_node_ptr->string, search_ptr->string) < 0)
  98.     {
  99.      search_ptr = search_ptr->left;
  100.     }
  101.    else
  102.     {
  103.      search_ptr = search_ptr->right;
  104.     }
  105.   }
  106.  if(strcmp(new_node_ptr->string, follow_ptr->string) < 0)
  107.   {
  108.    follow_ptr->left = new_node_ptr;
  109.   }
  110.  else
  111.   {
  112.    follow_ptr->right = new_node_ptr;
  113.   }
  114. }
  115.  
  116.  
  117.  
  118. void pre_order(tree_node *current_node)
  119. {
  120.  if(current_node != NULL)
  121.   {
  122.    cout << "HELLO" <<current_node->  string << endl;
  123.    pre_order(current_node->left);
  124.    pre_order(current_node->right);
  125.   }
  126. }
  127.  
  128.  
  129.  
  130. void dispose_of_tree(tree_node *current_node)
  131. {
  132.  if(!((current_node->left == NULL) && (current_node->right == NULL)))
  133.   {
  134.    if(current_node->right != NULL)
  135.     {
  136.      dispose_of_tree(current_node->right);
  137.     }
  138.    if(current_node->left != NULL)
  139.     {
  140.      dispose_of_tree(current_node->left);
  141.     }
  142.   }
  143.      cout << "GOODBYE" <<current_node->  string << endl;
  144.  delete current_node;
  145. }
Jan 30 '07 #1
3 4313
Ganon11
3,652 Recognized Expert Specialist
{ ROOT } //this is one tree
{ ROOT { FRED } } //this is one tree
{ ROOT { FRED { FRED_JUNIOR1 } { FRED_JUNIOR2} } }//this is one tree
{ ROOT
{ FRED
{ FRED_JUNIOR1}
{ FRED_JUNIOR2}
}
{ BARNEY
{ BARNEY_JUNIOR1}
{ BARNEY_JUNIOR2}
}
}// and this is the final tree
When inputting, you can keep a running count of how many open brackets you have by reading character by character. If you find an open bracket '{', add one - if you find a closed bracket '}', subtract one. Every time your total hits 0, you will have finished one tree.
Jan 30 '07 #2
wulfkat
3 New Member
Ok, so I tried to do what you said...

Expand|Select|Wrap|Line Numbers
  1. while (! textFile.eof())
  2.     {
  3.     getline (textFile, line);    
  4.     if (line.find("{"))
  5.     { 
  6.     oCount ++;
  7.     //cout << oCount << endl;
  8.  
  9. if (line.find("}"))
  10.                                 { 
  11.     oCount ++;
  12.     //cout << oCount << endl;
  13.                                 }
  14.  
  15.     //add the new string to the tree
  16.       strcpy(string, line.c_str()); 
  17.       add_to_tree(string);
And this is what I get:

HELLO{ ROOT }
HELLO{ ROOT { FRED } }
HELLO{ ROOT { FRED { FRED_JUNIOR1 } { FRED_JUNIOR2} } }
HELLO{ ROOT
HELLO{ FRED
HELLO { FRED_JUNIOR1}
HELLO { BARNEY_JUNIOR1}
HELLO
HELLO { BARNEY_JUNIOR2}
HELLO { FRED_JUNIOR2}
HELLO{ BARNEY
HELLO}
HELLO}
HELLO}
GOODBYE}
GOODBYE}
GOODBYE}
GOODBYE{ BARNEY
GOODBYE { FRED_JUNIOR2}
GOODBYE { BARNEY_JUNIOR2}
GOODBYE
GOODBYE { BARNEY_JUNIOR1}
GOODBYE { FRED_JUNIOR1}
GOODBYE{ FRED
GOODBYE{ ROOT
GOODBYE{ ROOT { FRED { FRED_JUNIOR1 } { FRED_JUNIOR2} } }
GOODBYE{ ROOT { FRED } }
GOODBYE{ ROOT }

which is not right at all....

Please help!
Jan 30 '07 #3
wulfkat
3 New Member
further along...no closer to the end...

code now


Expand|Select|Wrap|Line Numbers
  1.      if (textFile.is_open())
  2.      {
  3.     while (! textFile.eof())
  4.     {
  5.     getline (textFile, line, ' ');     
  6.  
  7.  
  8.     target = line.find("{",0);///found open brace
  9.     if(target != string::npos)
  10.     {
  11.     oCount ++;
  12.     line.erase(target, 1);
  13.     }
  14.     target1 = line.find("\t",0);  //found tab
  15.     if(target1 != string::npos)
  16.     {
  17.  
  18.                 line.erase(target1, 1);
  19.     }
  20.  
  21.     target3 = line.find(" ",0);  //found tab
  22.     if(target1 != string::npos)
  23.  
  24. {
  25.     line.erase(target1, 1);
  26.     }
  27.     target2 = line.find("}",0);//found closed
  28.     if(target2 != string::npos)
  29.     {
  30.  
  31.                oCount --;
  32.     line.erase(target2, 1);                                       }
  33.      //add the new string to the tree
  34.     if (line.length() > 3)
  35.     {
  36.            strcpy(string, line.c_str()); 
  37.           add_to_tree(string);
  38.         }
So now this is the output

HELLO ROOT
HELLO FRED
HELLO BARNEY

HELLO BARNEY_JUNIOR1

HELLO BARNEY_JUNIOR2
}
}

HELLO FRED
HELLO FRED_JUNIOR1
HELLO FRED

HELLO FRED_JUNIOR2
HELLO FRED_JUNIOR1

HELLO FRED_JUNIOR2
}

HELLO ROOT
HELLO ROOT
HELLO ROOT
GOODBYE ROOT
GOODBYE ROOT
GOODBYE ROOT
GOODBYE FRED_JUNIOR2
}

GOODBYE FRED_JUNIOR1

GOODBYE FRED_JUNIOR2
GOODBYE FRED

GOODBYE FRED_JUNIOR1
GOODBYE FRED
GOODBYE BARNEY_JUNIO
}
}

GOODBYE BARNEY_JUNIO

GOODBYE BARNEY

GOODBYE FRED
GOODBYE ROOT
Jan 30 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

7
3001
by: Kylotan | last post by:
I have a text file where the fields are delimited in various different ways. For example, strings are terminated with a tilde, numbers are terminated with whitespace, and some identifiers are terminated with a newline. This means I can't effectively use split() except on a small scale. For most of the file I can just call one of several functions I wrote that read in just as much data as is required from the input string, and return the...
7
2613
by: spike | last post by:
Im writing a program to search for a string in a binary file. And it works. The problem is: It is sooo slow! how can i make it faster? It takes 27 seconds just to search a 5 meg file. I guess it has something to do with the strequal() function... Btw, thanks to all of you who answered last time! code: ------------------------------------------------------------------------- #include <stdio.h>
2
2365
by: Profetas | last post by:
I have the following code that detects a <c> and </c> #include <stdio.h> main(int argc, char *argv) { FILE* fp; char data;
12
2992
by: Brian Henry | last post by:
first question... I have a flat file which unfortinuatly has columns seperated by nulls instead of spaces (a higher up company created it this way for us) is there anyway to do a readline with this and not have it affected by the null? because it is right now causes truncated data at wierd places... but as soon as i manually with a hex editor change char(00) to char(20) in the files it reads prerfectly... which leads me to my 2nd...
1
2590
by: j7.henry | last post by:
I am trying to pull specific data that is in a comma delimited file into a web page. So if my comma delimited file looks like: Name,Address,Zip Fred,123 Elm,66666 Mike,23 Jump,11111 I would like to be able to read this data and put each row into a variable? so I could display the values in a web page where I want.
1
1879
by: Jerry John | last post by:
I am working in ASP.NET with C#. I have a text file which contains datas with delimiters. For example:- MSH|^~\$|DISCHARGE|CLAY COUNTY MEMORIAL|||200502110939| I also have an XML file created with predefined tags. Some of the tags contain child element. I need to pass the data from the text file i.e the value within the delimiters should be passed to the corresponding tags within the XML file. I have done this through hard code. But i...
11
8658
by: Timofmars | last post by:
I'm try to Unload DB2 data from a table into a record sequential file on NT. I can an unload on Mainframe, but it doesn't seem to be an option in NT. In NT, all I can do is export/import. I can do a Load too, but not an Unload. I just want the only the data from the table in a record sequential file. Export seems only to give options to have a delimited line sequential file or a record sequential file where the data is preceeded by...
24
4457
by: Bill | last post by:
Hello, I'm trying to output buffer content to a file. I either get an access violation error, or crazy looking output in the file depending on which method I use to write the file. Can anyone help out a newbie? #include <stdio.h> #include <ctype.h> #include <string.h>
2
3932
by: Killer42 | last post by:
The Input #1 statement simply reads in one line from a text file (in this case you INI file) and places the values from it into one or more variables. So what you are reading in this statement is "#Please do not delete this file". My guess is that would all be placed in the first variable, a$. The information held in your file is much more complex than can be handled by a single Input # statement. Probably your best bet is to keep looping and...
1
1922
by: gopiganguly | last post by:
Hi everyone, There is a small problem encountered while creating a package in sql server 2005. Actually i am using a flat file which has 820 rows and 2 columns which are seperated by line feed(for ROW) and tab(for COLUMN).after importing i found that ther are only 800 rows imported into the table. Ather verifying the input file i found out that there are some null values in the second column so there is no line feed for those ...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10324
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8971
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.