-1

I'm working on a project that asks us to get input in a shape of pairs separated by a comma for example 2,16 16,134 15,631 those pairs will be saved into 2 vectors (1 for the numbers on the left and 1 for the numbers on the right of every pair) anyone has any idea of how to start on that ?

Maad98
  • 33
  • 5

3 Answers3

1

Don't make this harder than it has to be. You know that each pair will be of the form XYZ,XYZ and there'll be whitespace between pairs.

The stream extraction operator (>>), when reading into an int variable, will read all of the integer characters it can (ignoring leading whitespace) until it hits a non-integer character. We can use this to vastly simplify things.

In fact, your whole loop for reading in pairs just has to be:

int p1, p2;
char comma;
while(std::cin >> p1 >> comma >> p2) {
    //...
}

(Note that I'm using std::cin here. That can just as easily be swapped out for a file stream or--if you have a straight string--a stringstream).

See it in action here: ideone

scohe001
  • 15,110
  • 2
  • 31
  • 51
0

You can split the string on the spaces, creating an array of strings. You'll have something like {"2,16", "16,134", ...}.

Then you could split every one of these strings on the ,. For the first string in the array it would give you {"2", "16"}.

Parse the first string into the integer and add it into the first vector, parse the second string and add it into the second vector. Repeat it for every string in the initial array ({"2,16", "16,134", ...})

This may be helpful with splitting the strings, and this with parsing them into integers.

QmlnR2F5
  • 934
  • 10
  • 17
0

You can try something like this

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

std::pair<std::vector<int>, std::vector<int>> ExtractPairsFromString(const std::string& p_string)
{
    std::pair<std::vector<int>, std::vector<int>> result;

    std::stringstream   linestream(p_string);
    std::string         pair;

    while (getline(linestream, pair, ' '))
    {
        std::istringstream iss(pair);

        size_t delimiterPos = pair.find(',');

        std::string left = std::string(pair.begin(), pair.begin() + delimiterPos);
        std::string right = std::string(pair.begin() + delimiterPos + 1, pair.end());

        result.first.push_back(std::atoi(left.c_str()));
        result.second.push_back(std::atoi(right.c_str()));
    }

    return result;
}

int main()
{
    std::pair<std::vector<int>, std::vector<int>> result = ExtractPairsFromString("2,16 16,134 15,631");

    std::cout << "First vector (Left items):" << std::endl;
    for (const auto& element : result.first)
    {
        std::cout << element << std::endl;
    }

    std::cout << "Second vector (Right items):" << std::endl;
    for (const auto& element : result.second)
    {
        std::cout << element << std::endl;
    }

    std::cin.get();
    return 0;
}
Adrien Givry
  • 956
  • 7
  • 18