【问题标题】:std::cin with more complex objects带有更复杂对象的 std::cin
【发布时间】:2017-01-05 17:25:57
【问题描述】:

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

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 部分之前放一些随机词,希望当第一个循环失败时,第二个循环将从“红色”字符串开始读取,但它没有。

如何解决这个问题?

【问题讨论】:

  • 我们将不胜感激解释拒绝投票的原因。
  • 我没有投反对票,但我敢打赌,这是因为您在场外而不是直接在您的问题中发布了相关代码。 (以后请不要这样做。)
  • @ildjarn 相关代码都在问题中,我只跳过了&gt;&gt; 运算符重载,我觉得这里没有必要。 (当然还有 int main 和 co.)。我错了吗?我认为最好只留下最重要的部分而不是整个垃圾。

标签: c++ c++11 file-io c++14 iostream


【解决方案1】:

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

为了解决这个问题,在第一个循环中断后重置错误状态

std::cin.clear();

【讨论】:

    猜你喜欢
    • 2018-10-26
    • 2019-04-22
    • 2021-02-26
    相关资源
    最近更新 更多