c++ - 如何忽略输入流中的某些字符?

标签 c++

我需要从用户那里获得输入,这给了我红色,绿色和蓝色三种颜色,并以其相应的颜色打印出来。

输入的格式必须为(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 >>重载需要返回流,因为它在实现中已更改。

下面的代码在这里似乎可以正常工作:
我测试了(1,2,3),(0,255,0),(255,255,255),(127,0,1)...

#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;
}

由于您不会共享其余的代码(Color类/结构的定义),因此可以执行以下操作来验证operator >>是否正常工作:

读取值后立即打印它们!
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;
}

似乎在代码的其他地方,成员变量的值正在更改。

关于c++ - 如何忽略输入流中的某些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131007/

相关文章:

c++ - Visual Studio 2010 Qt 插件 Cmake 项目

c++ - 赋值运算符实现的解释

c++ - 在执行期间将父类转换为子类

c++ - 将 std::string 的 c_str() 结果分配给标准保证安全的同一个 std::string?

c++ - C argv指针类型

c++ - 在派生类中实现虚方法的问题

C++ 在 header 中使用声明与类型别名

c++ - QCombobox::setView 在 Windows 7 上崩溃应用程序

html - 如何在 QTableView 的一个单元格中提供多个链接

c++ - cin.fail()的错误处理问题