C++ 如何从C++;?

C++ 如何从C++;?,c++,C++,在程序中,假设我们从用户处获得一组整数,格式如下: std::cout << "Enter the new color value as: (red,green,blue)" << std::endl; string input; std::cin >> input; std::cout输入; 那么,从字符串中导出INT以进行操作的最有效的方法是什么?一个简单的方法是在结构中重载操作符>: struct Pixel { int red; int g

在程序中,假设我们从用户处获得一组整数,格式如下:

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

那么,从字符串中导出INT以进行操作的最有效的方法是什么?

一个简单的方法是在结构中重载
操作符>

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;
};
这允许您执行以下操作:

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

您可能希望在输入法中添加检查以获得正确的语法

根据问题和注释,我假设起点是一个
std::string
,比如:

std::string color { " ( 123, 1, 45 ) " };
目标是将这些数字减去,然后将其转换为整数。让我们首先删除空白:

color.erase(std::remove_if(color.begin(), color.end(), ::isspace), color.end());
现在,我们可以将数字提取为字符串:

std::regex reg("\\,");
std::vector<std::string> colors(
    std::sregex_token_iterator(++color.begin(), --color.end(), reg, -1),
    std::sregex_token_iterator()
);
std::regex reg(“\\,”);
向量颜色(
std::sregex_token_迭代器(++color.begin(),--color.end(),reg,-1),
std::sregex_令牌_迭代器()
);
最后,将它们转换为整数:

std::vector<int> integers;
std::transform(colors.begin(), colors.end(), std::back_inserter(integers),
           [](const std::string& str) { return std::stoi(str); });
std::向量整数;
std::transform(colors.begin()、colors.end()、std::back_插入器(整数),
[](const std::string&str){return std::stoi(str);});

related/dupe:据我所知,这只适用于枚举类,我正在寻找一些可以直接在这个原始代码上执行的东西,以类似main方法@NathanOliverOne的方式给我变量(没有错误检查):
cin>>red;cin.ignore();cin>>绿色;cin.ignore();cin>>蓝色
是否有理由首先将整个输入放入字符串中,而不是直接读取与某些
getchar
混合的整数?@Albjenow不,你可以这样做,尽管我不熟悉,你能用你所说的写一个答案吗?