Search code examples
c++parsingstringstream

C++ - Integer Parsing


I am struggling with the 'StringStream' problem from HackerRank. To be precise I am given a string of comma-separated integers, for example "23,4,56" and I need to parse them and return a vector of integers.

I have tried various ways to approach this problem, but they don't work for me.

This is the original code.

#include <sstream>
#include <vector>
#include <iostream>

using namespace std;

vector <int> parseInts(string str)
{
    // Function to complete.
}

int main()
{
    string str;
    cin >> str;

    vector <int> integers = parseInts(str);

    for (int i = 0; i < integers.size(); i++)
    {
        cout << integers[i] << "\n";
    }

    return 0;
}

This is my first idea, conversion with StringStream library.

vector <int> parseInts(string str) 
{
    stringstream ss(str); 
    int number;
    // To help with conversion.

    vector <int> temporary;
    // Vector of results.

    for (int i = 0; i < str.length(); i++)
    {
        ss >> number;
        temporary.push_back(number);
    }

    return temporary;
}

This is my second idea.

vector <int> parseInts(string str) 
{
    int number;
    vector <int> temporary;

    for (int i = 0; i < str.length(); i++)
    {
        number = (str[i]);
        temporary.push_back(number);
    }

    return temporary;
}

This is the last idea, I wanted to work on char*.

vector <int> parseInts(string str)
{
    char* characters;
    strcpy(characters, str.c_str());
    int numbers;
    vector <int> temp;

    for (int i = 0; i < str.length(); i++)
    {
        numbers = stoi(characters);
        temp.push_back(numbers);
    }

    return temp;
}

Apart from the last example they returned some weird numbers. How can I deal with it?


Solution

  • Your were almost there using your first approach, you need to use std::getline for separating using comma as delimiter.

    vector<int> parseInts(string str) 
    {
        stringstream ss(str); 
        string token;
        vector<int> v;
        while (getline(ss, token, ',')) {
            int x = stoi(token);
            v.push_back(x);
        }
    
        return v;
    }
    

    Here's the link where I tested it: https://ideone.com/JGOpS1