如果没有输入 getline 定界符,推荐一种抛出异常的方法?

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