如何预防 C++字符串流从 double 读入 int?
我想编写一个函数,该函数在遇到无效的输入时会从字符串中读取整数并引发错误。无效的输入包括非数字和非英式输入。以下功能将非数字输入视为无效输入,但不处理双输入。由于阅读到int只会抓住数字,何时达到”。它停止阅读。因此,如果用户传递“ 1.5”功能,下面的功能将返回“ 1”,但我期望有错误。如何处理双输入?
int ReadInt(const std::string& line) {
int entry{};
std::istringstream iss(line);
iss >> entry;
if (iss.fail()) {
// Throw Unexpected Input Exception
}
return entry;
}
I want to write a function that reads an integer from a string and throws errors when encountering invalid inputs. Invalid inputs include non-digit and non-integer inputs. The following function detects non-digit inputs as invalid input but does not handle double inputs. Since reading into int will just grab digits and when it reaches "." it stops reading. So if the user passes "1.5" the function below will return "1" but I am expecting an error. How can I handle double inputs?
int ReadInt(const std::string& line) {
int entry{};
std::istringstream iss(line);
iss >> entry;
if (iss.fail()) {
// Throw Unexpected Input Exception
}
return entry;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以检查是否消耗了整个输入。如果不是,那么输入包含的不仅仅是一个整数。如果您不想接受此类输入,则将此类输入视为无效并进行相应处理(抛出异常、再次询问输入等)
You can check whether the entire input was consumed. If it wasn't, then the input contained something more than just an integer. If you don't want to accept such input, then treat such input as invalid and handle it accordingly (throw exception, ask input again, etc.)