[Kstars-devel] Parser for something-delimited text files

Khudyakov Alexey alexey.skladnoy at gmail.com
Tue Jul 28 13:34:48 CEST 2009


Hello

There are a lot places in kstars where text files are read. Commonly they are 
something-delimited like "1 2 3" or "1:2:qwerty"

Code which does such parsing is usually bulky and hard to read. So it simple 
parser would be very useful. It will make code concise, easier to read and 
less error prone. 

### Brief API description 

Class methods:
# RecordParser(QString str, QString sep)
Create parser. Constructor mimics QString::split method. Other constructors 
could be added as needed.
  str - string to parse
  sep - separator to use.
 

# bool go();
Reset parser. Set internal pointer to beginning of list and clears error flag.

# bool checkLen(int n) 
Check length of list of records

# bool status() 
Return internal error flag. true means all is OK, false - error occured.

# operator(bool) 
Implicit coercion to bool. Mainly useful for shorthand notation. Same as 
status.

# RecordParser& operator >> (RecordParser&, T& x) 
Allow reading of element from list of records much like std::istreams. On 
errors set error flag

# RecordParser& operator >>(RecordParser&, Done) 
Special case. Set error flag if records list if not exhausted. Done is empty 
class used specially for this purpose. 




### Usage example 

Simple parser
> RecordParser parser("123:123:2.3",":")
> int i,j;
> double x
> parser >> i >> j >> x >> Done();
>
> if( !parser.status() )  std::cerr << "Could not parse string!" << std::endl;

Choice by length
> RecordParser parser("123:123:2.3",":")
> int i,j;
> double x
> if( parser.checkLen(3) {
>   parser >> i >> j >> x; // Done is ot needed there
> } else if( parser.checkLen(2) ){
>   parser >> i >> x;
> } else {
>   // This is error. Bad string 
> }
> if( !parser ) { // Here implicit coercion to bool is used. 

Alternatively in shorthand notation
> bool res = 
>   (parser.checkLen(3) && parser >> i >> j >> x) ||
>   (parser.checkLen(2) && parser >> i >> set(j,i) >> x);

--
  Khudyakov Alexey




More information about the Kstars-devel mailing list