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

Time:09-30

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];
        }
       
    }

CodePudding user response:

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.

  • Related