September 18th, 2003, 02:40 AM
parsing a text file
am a begginer and have been banging my head over a simple problem.
Using C++ I have to read from a text file which looks something like
3.949 4.949 c
2.343 4.454 c
4.454 3.34334 c
3.434 3.432 v
2.343 3.53555 v
the first line tells how many data points are there ...and then we have the x-coordinate and y-coordinate and a character c or v
i have to read this data strip out the number of lines (i.e is the first line......lines 30) from the text file and store it in a structure and make array out of the structure.
am stuck over this.......plzz help!!
Last edited by siddz; September 18th, 2003 at 12:39 PM.
September 18th, 2003, 10:01 AM
Don't know what your platform is, but most platforms do have a regular expression library.
These are bit cumbersome to use with C++ though.
Given the choice the best language for text processing still happens to be perl :-)
September 18th, 2003, 04:15 PM
Flip ahead in your book (I assume that you're using one or have one as a reference) to iostream. I'll give you a basic idea of what to look for, mainly because I work much more in C instead of C++ and because I never could see much use of streams -- but using them here will be the easier option for you.
Declare a file stream (of type ifstream if I recall correctly) and call its open method. Then use the input operator, >>, to read in each value. After you've read the line for the number of records, then it should look something like this:
There are a lot of details that I'm leaving out plus I could be making some mistakes here (remember, I don't normally use this), so be sure to review the material in your book.
// open ifile and read the first line to get the record count
// for each record
ifile >> try_record.x;
ifile >> try_record.y;
ifile >> try_record.t;
// now process that record; e.g. store it in an array
The thing that makes this easier for you is that ifstream will treat the spaces and newline as delimiters separating the values being read, so you don't have to deal with them explicitly.
Though I have to agree with e4c5 that the best language for text processing is perl. However, I've found some cases where I had a lot more control over the program with C. Everything's a trade-off.
Last edited by dwise1_aol; September 18th, 2003 at 04:18 PM.
September 18th, 2003, 05:32 PM
Perl may be a great language for text processing, but it's power is overkill here. This is a trivial program in C or C++. I have every confidence that our student will be able to handle his homework without resorting to perl.
September 18th, 2003, 06:34 PM
Ah, but wouldn't that be a great red herring?
He should know now what he needs to do. It's still up to him to figure out how to do it and how to make it work.
September 18th, 2003, 06:38 PM
Hey dwise1_aol, ClayDowling & e4c5 !!!
Thanks a lot guys!!! was able to parse the file as required....:D
u guys were of gr8 help...;)