C++ 如何忽略输入流中的某些字符?
我需要从用户那里获取输入,用户给了我3种颜色,分别是红色、绿色和蓝色,并以各自的颜色打印出来 输入的格式为(255255),每个逗号之间的数字范围为1到3位。我希望将每个整数分别存储为红色、绿色和蓝色,同时忽略括号和逗号C++ 如何忽略输入流中的某些字符?,c++,C++,我需要从用户那里获取输入,用户给了我3种颜色,分别是红色、绿色和蓝色,并以各自的颜色打印出来 输入的格式为(255255),每个逗号之间的数字范围为1到3位。我希望将每个整数分别存储为红色、绿色和蓝色,同时忽略括号和逗号 #include "color.h" #include <string> #include <iostream> Color::Color(): _reset{true}{ } Color::Color(int red, int green, in
#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,')');
}
#包括“color.h”
#包括
#包括
颜色::颜色():_重置{true}{
}
颜色:颜色(int红色、int绿色、int蓝色):_红色{red}、_绿色{green}、_蓝色{blue}、_重置{false}{
}
std::string Color::to_string()常量{
返回“(“+std::to_string(_red)+”、“+std::to_string(_green)+”、“+std::to_string(_blue)+”)”;
}
std::ostream和操作员过载。为什么这个实现不能像预期的那样工作?首先,您的操作符>
重载需要返回流,因为它在实现中已更改
下面的代码在这里似乎工作正常:
我用(1,2,3),(0255,0),(255255),(127,0,1)进行测试
出现在代码中的其他地方,成员变量的值正在改变。
我会考虑GETLIN,然后解析它。您可能也需要担心空白。但这样你就可以单元测试你的解析函数,而不必做实际的IOS。出于某种原因,这对我来说仍然不起作用。我使用输入(255,0,0),得到1196399479;32741m(0,-119639947932741:-861405333)
在输出中。您是完全使用了我发布的代码,还是更改了您的代码?另外,您使用的是什么环境?GCC,MSVC?x32、x64?我不知道“颜色”的类/结构定义,也不知道您使用的“重置”的目的。但是它在我提供的简单代码段上工作得非常好上次忽略后的代码>。我使用的是g++17。操作符>>
现在是正确的。问题应该在代码的其他地方。在输出该实例之前,是否还有其他事情发生在该实例上?请花点时间测试我提供的代码片段,这样我们就可以放弃任何与环境相关的问题。
#include <string>
#include <iostream>
struct Color {
int r, g, b;
std::string to_string() const;
};
std::string
Color::to_string() const
{
return
"{" + std::to_string(r) +
"," + std::to_string(g) +
"," + std::to_string(b) + "}";
}
std::istream&
operator>>(std::istream& ist, Color& color)
{
ist.ignore(1,'(');
ist >> color.r;
ist.ignore(1,',');
ist >> color.g;
ist.ignore(1,',');
ist >> color.b;
ist.ignore(1,')');
return ist;
}
int main()
{
Color color;
std::cout << "Insert color: ";
std::cin >> color;
std::cout << color.to_string() << std::endl;
return 0;
}
std::istream&
operator>>(std::istream& ist, Color& color)
{
ist.ignore(1,'(');
ist >> color.r;
ist.ignore(1,',');
ist >> color.g;
ist.ignore(1,',');
ist >> color.b;
ist.ignore(1,')');
std::cout << r << " " << g << " " << b << std::endl;
return ist;
}