Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I parse a string delimited by / into an array?

I have tried several methods of parsing a string and adding the elements to an array with using a / as a delimiter. I know I will eventually need to use stod(). Can anyone point me in the right direction? I will need to parse the string rec.

 void make_record() {

        int size = 4;
        double* record = nullptr;
        string rec;
        cout << "Enter record of items separated by a space " << endl;
        cout << "Item ID/Quantity/WholesaleCost/RetailCost" << endl;
        cin >> rec; // string to parse
        //Current: 12345 27.5 82.4 5.3
        //Goal: 12345/27.5/82.4/5.3
       
        //current approach
        record = new double[size];
        for (int i = 0; i < size; i++) {
            cin >> record[i]; 
        }

        //What I have tried - probably very wrong
        string delimiter = "/";

        size_t pos = 0;
        std::string token;
        while ((pos = rec.find(delimiter)) != std::string::npos) {
            token = rec.substr(0, pos);
            rec.erase(0, pos + delimiter.length());
            record[pos] = stod(token);
            cout << record[pos];
        }
       
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It’s really not a lot more complicated than your current approach.

    // better approach
    record = new double[size];
    for (int i = 0; i < size - 1; i++) {
        char slash;
        cin >> record[i] >> slash; 
    }
    cin >> record[size - 1]; 

The slash variable reads (and discards) the slashes in your input. Because the last number is not followed by a slash, it must be read separately, after the main loop.

Now this approach doesn’t do any error checking at all, but given correct input it works.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading