C++ 具有更复杂对象的std::cin
我有一个文本文件,它首先描述了一些行,然后描述了一些彩色行:C++ 具有更复杂对象的std::cin,c++,c++11,file-io,c++14,iostream,C++,C++11,File Io,C++14,Iostream,我有一个文本文件,它首先描述了一些行,然后描述了一些彩色行: 1 2 3 4 5 6 7 8 9 10 11 12 red 1 0 0 1 2 3 4 green 0 1 0 5 6 7 8 blue 0 0 1 9 10 11 12 执行时,每个部分中的行数未知 我重载了这些结构的std::cin>运算符: struct Point { int x, y; } struct Line { Point a, b; } str
1 2 3 4
5 6 7 8
9 10 11 12
red 1 0 0 1 2 3 4
green 0 1 0 5 6 7 8
blue 0 0 1 9 10 11 12
执行时,每个部分中的行数未知我重载了这些结构的
std::cin>
运算符:
struct Point { int x, y; }
struct Line { Point a, b; }
struct Color { float r, g, b; std::string name; };
struct ColorfulLine { Line line; Color color; };
(此处的完整示例:[已生效-根据接受的答案进行编辑]现在,我需要使用
行
和ColorfulLines
对文件进行迭代:
Line line;
while(cin >> line) { cout << "We've got a line!\n"; }
ColorfulLine color_line;
while(cin >> color_line) { cout << "We've got a colorful line!\n"; }
// actually I'm putting them into std::lists but I skipped this part for simplicity
行;
当(cin>>line){cout>color\u line){cout在第一个循环中断后,std::cin
处于不良状态。这就是循环首先中断的原因。对不良流执行读取会立即失败,因此第二个循环永远不会进入
要解决此问题,请在第一个循环中断后使用重置错误状态
std::cin.clear();
请解释拒绝投票的原因。我没有拒绝投票,但我敢打赌,这是因为您在场外发布了相关代码,而不是直接在您的问题中发布。(请以后不要这样做。)@ildjarn所有相关代码都在问题中,我只跳过了>
操作符重载,我发现这里不必要。(当然还有int main和co。)我错了吗?我想我最好只留下最重要的部分,而不是整个垃圾。