推荐一种在未输入获取行分隔符时引发异常的方法?
Recommend a way to throw an exception if a getline delimiter isn't entered?
我得到一行,例如Array has size: 4
从 cin 和我想首先检查字符串是否正是这个,其次提取整数。 我找到了读取字符串并提取整数的方法:
string start;
getline (cin, start, ':' );
if (start != "Array has size")
{
throw MyException("Wrong format");
}
但我的问题是,如果读取的行没有:
,那么它只是继续等待一个并且程序卡住了。我无法start
检查字符串以确保它有一个:
,因为如果有的话,它已经被getline
消耗了。
我无法让getline
阅读 14 个字符,因为我相信这只有char*
才能实现? 有没有一种干净的方法可以做到这一点,如果字符串不匹配而不会卡住,我想抛出一个异常。它是否涉及以某种方式逐步执行字符串?我发现的其他问题似乎并没有完全解决这个问题。 任何方向都非常感谢!
调用没有
分隔符的std::getline()
将整行读入std::string
,然后根据需要使用 std::istringstream
解析该行,例如:
string line;
getline (cin, line);
istringstream iss(line);
string start;
getline (iss, start, ':');
if (start != "Array has size")
{
throw MyException("Wrong format");
}
int number;
if (!(iss >> number))
{
throw MyException("Wrong format");
}
不要忘记std::scanf
:
#include <cstdio>
std::size_t s;
if (std::scanf("Array has size: %zu", &s)) {
// ...
}
else {
throw MyException("Wrong format");
}
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 当用户键入分隔符时,停止getline()输入
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 为什么在逗号分隔符上下文中将预增量的结果强制转换为void
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 如何在 c++ 中使用 ',' 作为 getline 分隔符
- 尝试使用智能指针时引发异常
- 推荐一种在未输入获取行分隔符时引发异常的方法?