gpt4 book ai didi

C++ 指定来自 istream 的输入并测试它

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:41:43 25 4
gpt4 key购买 nike

我有一个基本上表示元组(双 x,双 y)的类,我已经重载了 << 运算符,所以我可以打印该类。现在我想对 >> 做同样的事情,所以它只支持以下格式:x, (x) 和 (x,y)。

我有以下代码:

std::ostream & operator<< (std::ostream &output, tuple &c){
output << "(" << c.x << "," << c.y << ")" << endl;
return output;
}

std::istream & operator>> (std::istream & input, tuple &c){
// Check for following patterns: x, (x) or (x,y)
}

我可以遍历输入和正则表达式匹配吗?那怎么办呢?另外我怎么能测试它是否真的有效,就像这样 std::cin >> "(10.2,5.5)"
还是我需要从文件中读取以进行测试?

编辑:给出的答案确实解决了这个问题,但我想添加一种方法来测试它,因为它可能会使用除我以外的其他人:

tuple x(6,2);
stringstream ss;
ss << x;
ASSERT_EQUALS(ss.str(), "(6,2)\n");

最佳答案

正则表达式对于像这样的简单输入任务来说是不必要的。以下是我的做法,不检查输入是否有效,只是解析:

std::istream & operator>> (std::istream & input, tuple &c){
// Check for following patterns: x, (x) or (x,y)
char firstCharacter;
input >> firstCharacter; // See what the first character is, since it varies

if (firstCharacter == '(')
{ // The simplest case, since the next few inputs are of the form n,n)
char delimiters;
input >> c.x >> delimiters >> c.y >> delimiters;
// N , N )
// You also here have to check whether the above inputs are valid,
// such as if the user enters a string instead of a number
// or if the delimeters are not commas or parentheses
}
else if (isdigit(firstCharacter) || firstCharacter == '-')
{ // For negative numbers
char delimiters;
input.unget(); // Put the number back in the stream and read a number
input >> c.x >> delimiters >> delimiters >> c.y >> delimiters;
// N , ( N )
// You also here have to check whether the above inputs are valid,
// such as if the user enters a string instead of a number
// or if the delimeters are not commas or parentheses
}
else
{
// Handle some sort of a parsing error where the first character
// is neither a parenthesis or a number
}

return input;
}

关于C++ 指定来自 istream 的输入并测试它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48664037/

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