gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:49:27 33 4
gpt4 key购买 nike

我正在排队,例如
数组大小: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");
}

关于c++ - 如果没有输入 getline 定界符,推荐一种抛出异常的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389106/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com