【发布时间】: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 >> neighbours[i]时捕获,而 neighbours[i] 是 int 类型 -
不太清楚
neighbours[i];始终是int。也许您想将输入读取为字符串并首先检查它是否为整数 -
@idclev463035818 猜测这可能有效,然后如果 main 方法不是 int 则向 main 方法抛出异常?
-
我想我终于明白了你想要什么,有一种方法可以启用
cin抛出异常,但它的使用非常罕见,以至于我没有找到好的副本,这可能会有所帮助:stackoverflow.com/a/26187787/4117728