stl - How to read badly formatted input data in C++? -


i learning c++ , stuck on exercise. how read data not formatted correctly? example, given file need read data looks this:

1   z 2 1   xy 2 3   8000  e 1777  e 2001 

the first, second, , third lines make "module". there lot of data many modules input through keyboard. program has accept of user's input (until user decides type "q" quit) , read input , manipulate data. ideally, input formatted correctly example above, data have whitespace, tabs, carriage returns, or start data previous module, this:

2   r 5001  e 4777 1   z 2     1   xy 2 3   8000  e 1777 e 2001 

what best way read , manipulate input data bad formatting? in case want able extract 1 z 2, 1 xy 2, , 3 8000 e 1777 e 2001 , store in array or kind of stl container , able information later (like add, subtract, or multiply number based on whether there "a", "s", or "m" in front of number).

my program has able recognize z , xy variables , z = 2 , xy = 2.

you better answers if described logical purpose of parts of input better. i'm going guess each module starts count of how many variable name/numeric-value pairs follow, allows more structured approach reading , storing values. populate vector (array) of maps (binary trees) variable name value, convenient later lookups , processing.

std::vector<std::map<std::string, int>>> vars; int vars_in_module; while (cin >> vars_in_module) {     vars.emplace_back();  // add empty module vector     std::string identifier;     int value;     (int = 1; <= vars_in_module; ++i)         if (cin >> identifier >> value)             vars.back()[identifier] = value;  // add var module         else         {             std::cerr << "error parsing variable identifier & value\n";             exit(1);         } } 

the map re-sort lexicographically (using ascii order of left-most character, - if that's equal - 1 right etc.) rather preserve order in typed, may or may not matter depending on use put variables. maps fast search particular identifier later, use vector if cared input order.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

python - pip wont install .WHL files -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -