【问题标题】:C++ Throwing istream specific errors when parsing a fileC++ 解析文件时抛出 istream 特定错误
【发布时间】:2020-04-08 12:43:44
【问题描述】:

嗨,我的主要方法中有这一行:

std::copy(std::istream_iterator<Constituency>(inputFile), std::istream_iterator<Constituency>(), std::back_inserter(constits));

这会将文件解析为向量。我已经覆盖了std::istream << 运算符重载,并且正在寻找在解析失败时抛出特定错误消息的方法。这是

std::istream& operator>> (std::istream& input, Constituency& constituency) {

    int num_neighbours;
    input >> num_neighbours;
    std::string name;
    std::vector<int> neighbours(num_neighbours);

    for(int i = 0; i < num_neighbours; i++) {
        try{
            input >> neighbours[i];
        } catch(...) {
            std::cout << "Error: Int Neighbour" << std::endl;
        }
    }
    try{
        input >> name;
    } catch(...) {
        std::cout << "Error: Expected String Name" << std::endl;
    }

    constituency = Constituency(name, neighbours);

    return input;
}

错误消息不会被打印出来。我该如何更改它,以便如果在预期 int 的地方遇到字符串,它会抛出错误,反之亦然。

【问题讨论】:

  • 分段错误不是 C++ 异常,try catch 无法捕捉到。
  • @some[rpgrammerdude 我不希望它捕获分段错误我希望它在尝试使用字符串 input &gt;&gt; neighbours[i] 时捕获,而 neighbours[i] 是 int 类型
  • 不太清楚neighbours[i]; 始终是int。也许您想将输入读取为字符串并首先检查它是否为整数
  • @idclev463035818 猜测这可能有效,然后如果 main 方法不是 int 则向 main 方法抛出异常?
  • 我想我终于明白了你想要什么,有一种方法可以启用cin 抛出异常,但它的使用非常罕见,以至于我没有找到好的副本,这可能会有所帮助:stackoverflow.com/a/26187787/4117728

标签: c++ exception istream


【解决方案1】:

当输入操作失败时,会在流上设置一个“failbit”。

您可以使用“if”语句检查这一点:

input >> neighbours[i];
if (!input) {
   std::cout << "Error: Int Neighbour" << std::endl;
}

或者:

if (!(input >> neighbours[i])) {
   std::cout << "Error: Int Neighbour" << std::endl;
}

但是,除了couting,您还需要对这种糟糕的输入采取一些措施。如果您不打算只“返回”,则必须跳过一行,或跳过一些字节,或执行您认为合适的任何操作。还要用std::cout.clear()清除错误状态,否则没有进一步的输入操作成功。

【讨论】:

    猜你喜欢
    • 2017-07-15
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多