Libra
Libra

Reputation: 2595

How to derive ints from formatted string in C++?

In a program, lets say we get a set of integers from the user in the following format:

std::cout << "Enter the new color value as: (red,green,blue)" << std::endl;
string input;
std::cin >> input;

What would then be the most well-practiced way to derive the ints from the string for operation?

Upvotes: 2

Views: 127

Answers (2)

mfnx
mfnx

Reputation: 3018

From the question and comments, I'll assume the starting point is a std::string like:

std::string color { " ( 123, 1, 45 ) " };

The goal is to substract those numbers and convert them into integers. Let's first remove the white spaces:

color.erase(std::remove_if(color.begin(), color.end(), ::isspace), color.end());

We can now extract the numbers as strings:

std::regex reg("\\,");
std::vector<std::string> colors(
    std::sregex_token_iterator(++color.begin(), --color.end(), reg, -1),
    std::sregex_token_iterator()
);

Finally, convert them to integers:

std::vector<int> integers;
std::transform(colors.begin(), colors.end(), std::back_inserter(integers),
           [](const std::string& str) { return std::stoi(str); });

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57678

A simple method is to overload the operator>> in your struct:

struct Pixel
{
  int red;
  int green;
  int blue;
  friend std::istream& operator>>(std::istream& input, Pixel& p);
};

std::istream& operator>>(std::istream& input, Pixel& p)
{
  char c;
  input >> c; // '('
  input >> p.red;
  input >> c; // ','
  input >> p.green;
  input >> c; // ','
  input >> p.blue;
  input >> c; // ')'
  return input;
};

This allows you to do something like this:

Pixel p;
std::cout << "Enter the new color value as: (red,green,blue)" << std::endl;
cin >> p;

You may want to add checks to the input method for correct syntax.

Upvotes: 2

Related Questions