【发布时间】:2020-02-09 07:06:21
【问题描述】:
我需要从用户那里获取输入,它给了我红色、绿色和蓝色 3 种颜色,并以各自的颜色打印出来。
输入的格式必须为 (255,255,255),每个逗号之间的数字范围为 1 到 3 位。我想将每个整数分别存储在 _red、_green 和 _blue 中,同时忽略括号和逗号。
#include "color.h"
#include <string>
#include <iostream>
Color::Color(): _reset{true}{
}
Color::Color(int red, int green, int blue): _red{red}, _green{green}, _blue{blue}, _reset{false}{
}
std::string Color::to_string() const{
return "(" + std::to_string(_red) + "," + std::to_string(_green) + "," + std::to_string(_blue) + ")";
}
std::ostream& operator<<(std::ostream& ost, const Color& color){
if(color._reset==false){
ost << "\033[38;2;" << std::to_string(color._red) << ";" << std::to_string(color._green) << ";" << std::to_string(color._blue) << "m";
}else{
ost << "\033[0m\n";
}
return ost;
}
std::istream& operator>>(std::istream& ist, Color& color){
ist.ignore(1,'(');
ist >> color._red;
ist.ignore(1,',');
ist >> color._green;
ist.ignore(1,',');
ist >> color._blue;
ist.ignore(1,')');
}
有问题的问题在于 operator>> 重载。为什么这个实现没有按预期工作?
【问题讨论】:
-
我会考虑getline,然后解析它。您可能还需要担心空格。但是这样你就可以对你的解析功能进行单元测试,而无需进行实际的 IO
标签: c++