推荐一种在未输入获取行分隔符时引发异常的方法?

Recommend a way to throw an exception if a getline delimiter isn't entered?

本文关键字:分隔符 异常 方法 获取 输入 未输 一种      更新时间:2023-10-16

我得到一行,例如

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");
}