StringStream

  • + 0 comments

    A lot of people rewriting the wheel, here. The example mentions ss >> a, so do not get confused by all of the people not using the basic ss >> method.

    vector<int> parseInts(string str) 
    {
        // StringStream to store our string for easy output
        stringstream ss(str);
        // Integer for storing the size of our final number array.
        // We start this at 1, as there is 1 more number than comma.
        int n = 1;
        // Character to provide a buffer, when reading.
        char c;
    		
        // First, go through the array, and count the commas.
        // Each comma means another number.
        for(int i = 0; i < str.size(); i++) if(str[i] == ',') n++;
        // Now we know how many numbers there are, 
        // create the number array.
        vector<int> array(n);
        // For each number in the string, pass it into the array, 
        // and than pass the comma into the character buffer.
        for(int j = 0; j < n; j++) ss >> array[j] >> c;
    		
        // Return our completed array.
        return array;
    }