【问题标题】:How to ignore certain characters in an input stream?如何忽略输入流中的某些字符?
【发布时间】: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++


【解决方案1】:

首先,您的operator &gt;&gt; 重载需要返回流,因为它在实现内部发生了变化。

下面的代码在这里似乎可以正常工作: 我测试了 (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 &gt;&gt; 是否正常工作:

阅读后立即打印这些值!

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

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

【讨论】:

  • 出于某种原因,这对我仍然不起作用。我使用了输入 (255,0,0),我在输出中得到了1196399479;32741m(0,-1196399479,32741:-861405333)。
  • 您是否使用了我发布的代码,或者您是否更改了您的代码?另外,你用的是什么环境?海合会,MSVC? x32、x64?
  • 我不知道“颜色”的类/结构定义,也不知道您正在使用的“重置”的目的。但它在我提供的简单 sn-p 上运行良好。
  • 我更改了我的代码,我只是在最后一次忽略后添加了return ist;。我正在使用 g++17。
  • operator &gt;&gt; 现在是正确的。问题应该在代码中的其他地方。在输出之前,实例是否发生了任何其他事情?请花点时间测试我提供的 sn-p,以便我们排除任何与环境相关的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-09
  • 1970-01-01
  • 2017-02-16
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2014-11-03
相关资源
最近更新 更多