Search code examples
c++string-parsing

Need to extract ifstream into separate arrays based upon type of data read


C++ noob here. I'm working on a program which needs to include the ability to read data from an input stream, then separate the data into two separate arrays based on the type of data read (an integer array and a string array).

The data in the input files is presented in the following format (without the spaces in between the lines):

5000 Leather Seats

1000 DVD System

800 10 Speakers

etc.

I need to separate the prices (numeric values at the beginning of each line) from the description of each (the rest of the contents of each line) into two separate strings ("prices" and "options"). Could someone point me in the right direction to find the most efficient way of reading the appropriate data from each line into its respective array?


Solution

  • Probably the easiest way to do this is use getline to get the full line as a string, then uses substrings to split it up, then add to the arrays. for example:

    string s;
    getline(cin,s);
    string price = s.substr(0, s.find(" "));
    string type = s.substr(s.find(" ")+1, s.length());
    

    add price and type to respective arrays.