多条获取线实现

Multiple getline implementation

本文关键字:实现 获取      更新时间:2023-10-16

我通常使用std::getline来读取在线编程挑战的控制台输入,现在已经解决了相当多的问题,我已经厌倦了编写多个std::getline(std::cin, str1); std::getline(std::cin, str2); std::getline(std::cin, str3);...

所以我使用可变参数模板编写了自己的多个阅读行,我只需要快速查看这是否正确,因为在我看来getlines(first)没有返回?如果s1上没有任何输入,while还会评估吗?

#include <iostream>
#include <string> //getline
#include <type_traits> //std::is_same
template<typename F>
std::istream& getlines(F& first)
{
return std::getline(std::cin, first);
}
template<typename F, typename...O>
std::istream& getlines(F& first, O&... others)
{
static_assert(std::is_same_v<decltype(first), std::string&>, "error: template getlines must be of std::string type");
getlines(first); //how is this returned?
return getlines(others...);
}
int main()
{
std::string s1, s2, s3;
while (getlines(s1, s2, s3))
{
std::cout << s1 << s2 << s3 << std::endl;
}
}
在我看来

getlines(first)没有返回?如果s1没有输入任何内容,仍然会评估吗?

获取线的返回值为istream &...而且确实没有使用。 不过,这并不重要,因为无论哪种方式,您都可以引用该流(std::cin(。 因此,即使由于EOF或其他条件而无法设置s1,相应的标志也会std::cin中设置,因此一旦您返回它(最后这样做(,它就会在while循环的条件下进行测试。

这里错失的机会是,当第一个getlines已经失败时,您可以提前退出。例如:

template<typename F>
std::istream& getlines(F& first)
{
return std::getline(std::cin, first);
}
template<typename F, typename...O>
std::istream& getlines(F& first, O&... others)
{
static_assert(std::is_same_v<decltype(first), std::string&>, "error: template getlines must be of std::string type");
if (! getlines(first)) return std::cin;
return getlines(others...);
}

顺便说一句,这是我想到的:

template<typename... Strings>
std::istream & getlines(Strings &... strings) {
for (auto & str : {std::ref(strings)...}) {
if (! std::getline(std::cin, str.get())) break;
}
return std::cin;
}