std::cin 对象更复杂

std::cin with more complex objects

我有一个文本文件,它首先描述了一些线条,然后描述了一些彩色线条:

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

(此处的完整示例:http://ideone.com/bMOaL1 [已经有效 - 根据接受的答案进行编辑])
现在我需要使用 LinesColorfulLines:

遍历文件
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

这就是问题所在 - 从未获取彩色线条,即未执行第二个循环。

我有一个假设为什么会发生但不知道如何解决:
std::cin 试图获取第 4 行时,它失败了,因为没有数字而是字符串 "red".
接下来,在第二个 while 循环中,std::cin 尝试读取一个字符串 (Color.name) 但它看到一个数字,然后也失败了。

我试图在 ColorfulLines 部分之前放置一些随机词,希望当第一个循环失败时,第二个将开始从 "red" 字符串读取,但它没有。

如何解决?

第一个循环中断后,std::cin 状态不佳。这就是循环首先中断的原因。对坏流执行读取会立即失败,因此永远不会进入第二个循环。

要解决此问题,请在第一个循环中断后重置错误状态

std::cin.clear();