Solved

Parsing a text file

Posted on 2003-11-24
22
303 Views
Last Modified: 2010-04-02
new to c++

i am reading in a text file and i am trying to get it in 15 line blocks and then set that to an array which i then grab some elements from

i can open the file ok, use getline to get the line -- what i am not sure of is how to grab 15 lines in the text file and then set that to an array


0
Comment
Question by:tpiazza
  • 9
  • 9
  • 2
  • +2
22 Comments
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9812946
I assume you've known how to use getline to get a line. Then what's wrong with using a loop counting to 15 to do this 15 times (you might want to use a 2 dimensional array maybe)?
0
 
LVL 11

Expert Comment

by:bcladd
ID: 9812952
(1) An array of what? If you're using getline you're either getting characters (in a buffer of some sort: a char array?) or std::string. So, depending on how you use getline (you'll want to show us your code) and what you want an array of, the answer is different.

(2) If you KNOW there will always be 15 lines to read, you can use a simple count-controlled loop (a for loop) to read 15 lines. I guess I am not sure where that part of the assignment is hanging you up.

-bcl
0
 

Author Comment

by:tpiazza
ID: 9813192
here is what i have

basically i need to read through the comma delimited file line by line and find the one that has KTC as its first value  then read that whole line and output it


#include <iostream.h>
#include <string.h>    
#include <fstream.h>
#include <stdlib.h>

int main ()

{
  char buffer[1000];
  char dataline[1000];

  ifstream thefile ("c://file.txt");
 
  if (! thefile.is_open())
  { cout << "Error opening file"; exit (1); }

  while (! thefile.eof() )
  {
      thefile.getline ( buffer, 100, ',');

      if(strcmpi("KTC", buffer))  
      {
      
      thefile.getline (dataline, 500, ',');
      cout << dataline << endl;

      }
   
            
  }
  return 0;
}
0
 

Author Comment

by:tpiazza
ID: 9813207
in vb there is a split function -- i cant find one for c++
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9813403
Why don't you use std::string? There is a substr method that allows you to extract a substring of that string.

string str = "ABCDE";
cout << str.substr(0,3) << endl;
0
 
LVL 11

Expert Comment

by:bcladd
ID: 9813407
From Koenig and Moo's _Accelerated C++_ (http://www.acceleratedcpp.com/):

using std::find_if;
using std::string;
using std::vector;

using std::isspace;

// `true' if the argument is whitespace, `false' otherwise
bool space(char c)
{
      return isspace(c);
}

// `false' if the argument is whitespace, `true' otherwise
bool not_space(char c)
{
      return !isspace(c);
}

vector<string> split(const string& str)
{
      typedef string::const_iterator iter;
      vector<string> ret;

      iter i = str.begin();
      while (i != str.end()) {

            // ignore leading blanks
            i = find_if(i, str.end(), not_space);

            // find end of next word
            iter j = find_if(i, str.end(), space);

            // copy the characters in `[i,' `j)'
            if (i != str.end())
                  ret.push_back(string(i, j));
            i = j;
      }
      return ret;
}


This actually splits on spaces (and uses std::string and iterators all over the place) but by modifying the code for the boolean functions you should be able to make it split anything you want.

The book is really, really good, too. (A readable language introduction.)

Hope this helps, -bcl
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9813448
And use
getline(thefile, str, ','); instead of thefile.getline(...); because the latter does not take a string parameter.
0
 

Author Comment

by:tpiazza
ID: 9818580
how do i read in the stream set to an array and then grab the element

getline is giving me whatever char is at the place i specify.  i need the whole element

#include <iostream.h>
#include <string.h>    
#include <fstream.h>
#include <stdlib.h>



int main ()

{      char buffer[100];
 
  ifstream thefile ("c://file.txt");
 
  if (! thefile.is_open())
  { cout << "Error opening file"; exit (1); }

  while (! thefile.eof() )
  {
         thefile.getline ( buffer,  '/n');
      
  cout << buffer[4] << endl;
            
  }
  return 0;
}
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9819015
Your filename should be "c:\\file.txt" or "c:/file.txt", not "c://file.txt". And it's '\n' not '/n'. And you are displaying the buffer's 4th character. try cout << buffer << endl;
0
 

Author Comment

by:tpiazza
ID: 9819238
i know im displaying the fourth character -- how do I get the forth element

each line looks like

ktc, 3,3,11,27,00,040,00,29,66,108,50,30,06,227,00*4D

when it grabs this using getline how do i set it to an array and then grab the fourth element?

0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9819274
well, that's simple then.
You can grab the first string "ktc" or whatever it is, using getline.
thefile.getline(buffer, <size goes here>, ','); //get up to the comma.
after that you can use >> to get the numbers.
int num;
char ch;
for(int i = 0; i < 4; ++i) {
   thefile >> num; //get the number after 4 times you will get in sequence: 3 3 11 27.
   thefile >> ch;  //get the comma. Note that >> skips spaces.
}

//now num contains 27.
Works for you?
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

by:tpiazza
ID: 9819668
it goes to some wierd loop and spits nothing but zero out

i deleted everythng out of the file except

ktc, 3,3,11,27,00,040,00,29,66,108,50,30,06,227,00*4D

here is what i have:

#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>



int main ()

{      char buffer[500];
      int num;
      char ch;

      ifstream thefile;
      thefile.open ("c:\\file.txt", ios::in);

  if (! thefile.is_open())
  { cout << "Error opening file"; exit (1); }

  while (! thefile.eof() )
  {

         thefile.getline(buffer, ','); //get up to the comma.

      for(int i = 0; i < 4; ++i)
      {
   
            thefile >> num;
            thefile >> ch;  
      }
      
  cout << num  << endl;
 
  }

  thefile.close();
  return 0;
}
0
 

Author Comment

by:tpiazza
ID: 9819685
thefile.getline(buffer, <size goes here>, ',');

the size can vary from 4 to 31 characters

i assume

thefile.getline(buffer, ','); works
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9819721
You misused getline. Look at the syntax I cited:
>>thefile.getline(buffer, <size goes here>, ','); //get up to the comma.
so the called should have been getline(buffer, 499, ',');
you called getline(buffer, ',');
thus ',' is interpreted as a size, and yields an ASCII value of 50 something. That's why you can't get anything else because the entire line was read into buffer (',' was no longer a delimiter)
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9819725
<size> stands for the maximum characters your array can sustain/ or the maximum you WANT to get into that array.
0
 

Author Comment

by:tpiazza
ID: 9824516
still get nothing but a bunch of zeros

even though i changed it to

thefile.getline(buffer, 499, ',');

      
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 9826510
The code worked fine for me:

#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

int main () {
   char buffer[500];
   int num;
   char ch;

   ifstream thefile;
   thefile.open ("file.txt", ios::in);     /////Notice I changed the path because I was running this on remote UNIX
                                                    ////and it does not have access to my C Drive.
                                                    ////If you want you can change it back to what you have "C:\\thefile.txt"
   if (! thefile.is_open()) {
      cout << "Error opening file";
      exit (1);
   }

   while (! thefile.eof() ) {
      thefile.getline(buffer, 499, ','); //get up to the comma.

      for(int i = 0; i < 4; ++i) {
         thefile >> num;
         thefile >> ch;
      }

      cout << num  << endl;
  }

  thefile.close();
  return 0;
}

with the content of file.txt exactly like so:
ktc, 3,3,11,27,00,040,00,29,66,108,50,30,06,227,00*4D

The output I get is:
27  //The fourth number
66  //skip 00, get the fourth number after that. which is 66
227 //skip 108, get the fourth number after that. which is 277
227 //skips 00*4D, and get to end of file. Thus num remains the same as 277.

Please check your syntax again and let me know :)
0
 

Author Comment

by:tpiazza
ID: 9850102
i cut and pasted your code

now i get -858993460

0
 

Author Comment

by:tpiazza
ID: 9906041
please delete -- someone else answered this
0
 
LVL 9

Expert Comment

by:tinchos
ID: 10285781
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

PAQ with points refunded

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer
0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 10287194
The code I posted, worked fine for me. The asker never followed up, simply just said "someone else answered this." That's reasonable enough =/, is it?.
0
 

Accepted Solution

by:
SpazMODic earned 0 total points
ID: 10347362
PAQed, with points refunded (75)

SpazMODic
EE Moderator
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now