Povylas
Povylas

Reputation: 786

How to read complex text file in c++?

A text file I what to read has a certain pattern:

Name line [tag name 452,54 | tag2 name 323,2 | tag3 name 252,25 ... ]
Name2 line [tag name 422,54 | tag2 name 33,2 | tag3 name 111,525 | tag4 name 222,2 ... ]

The most troublesome part of dealing with this file is the number of tags per each line is not set.

I was trying to make it work by reading file line by line and exploding the lines into variables using scanf() because it seamed to be good at reading patterns. But tag name word count is not set, so it was not much of a help either.

I can manipulate file pattern a bit without losing any data to make it easier to read but no solution have crossed my mind. Examples of how can I manipulate file pattern:

Name line 
tag name 452,54 | tag2 name 323,2 | tag3 name 252,25 ... 
Name2 line 
tag name 422,54 | tag2 name 33,2 | tag3 name 111,525 | tag4 name 222,2 ... 

I added [] and | symbols as separators but ideally the less of them the better.

Name line 
tag name 452,54 
tag2 name 323,2
tag3 name 252,25 ... 
Name2 line 
tag name 422,54
tag2 name 33,2
tag3 name 111,525
tag4 name 222,2 ... 

If you have read with similar patterns please share. I am a bit stuck now...

EDIT: It is a simple .txt file and I chose tags name and name line as substitutes for any string value. There are no id or something else to make it easy.

Upvotes: 1

Views: 753

Answers (3)

Klaas van Gend
Klaas van Gend

Reputation: 1128

If you really must write your own code and maintain newline to have the special meaning, of tag separation, you could use a combination of fgets() and strtok(). http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Upvotes: 0

pmr
pmr

Reputation: 59811

Instead of mangling your file until you can read it, you should look closely at the grammar that defines your file format and build a small parser. While the task may look daunting at first, it is not that difficult.

I prefer Boost.Spirit for such tasks.

Upvotes: 1

Akshaya Shanbhogue
Akshaya Shanbhogue

Reputation: 1448

Looks like you are searching for a parser. There are lots of them online. :) Even lex/yacc or bison or something can help out.

Upvotes: 1

Related Questions