Reputation: 1468
I have a sample file where a line looks like this: CAR;FORD;FIESTA;WHITE;20300;19900;23555
Now i need to parse this line where first four attributes should be stored separately and for last three(or more) an average needs to be calculated ("choosing the right approach" in progress...)
When I successfully tokenize this I need to pass these tokens to a class that has a separate (public)variable for each attribute
class ClassA{ //aggregate class
public:
string vehicle;
string brand;
string model;
string color;
double avgPrice;
//...
};
What is the most appropriate approach?
When tokenizing, should I store all tokens in an array and then pass
the array as parameter and then add a initialization lists to a
ClassA
constructor where i assign each corresponding Arr[n]
to
an attribute?
Or should I rather make a temp variable for each attribute and then do the standard initialization list. But this would make awful clumsy code, where i'd have to repeat the same thing 4 times each time storing a token in a different variable.
Feel free to offer an even better solution, for i am mere beginner in C++ and my knowledge of it's capabilities is basic.
Upvotes: 1
Views: 669
Reputation: 726987
Rather than solving this as a monolithic task, consider separating it into two parts:
ClassA
This separation insulates ClassA
from the responsibility of reading a string representation. This is a good thing: it lets you change this string representation later on, without having to change your ClassA
to match the new representation.
The first task (tokenization) can be solved in a generic way: all you need to do is reading from a string, and storing parts into a collection. I would suggest using std::vector<std::string>
instead of an array, assuming that you can use C++ collections for this problem.
The second task starts with a list of tokens. Most of your tokens are passed to ClassA
as strings, so you simply pass them to a constructor that uses the standard initialier list. The last parameter needs additional conversion from string
to a double
. This should be done outside ClassA
constructor, to maintain clean separation of responsibilities.
Upvotes: 1
Reputation: 355
for me there are two solutions :
Usually, the attributes of a class must be private, or even protected. But have a direct access on these attributes OUTSIDE of the class avoids your class to control the values goin in and out.
If your class is dedicated to parsing, the solution 1 is for me the best. Otherwise, prefer the second solution : just parse your string and give a string vector as an arg in a function of your class(or even the constructor).
Upvotes: 2