我通常使用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;
}
}发布于 2019-12-15 23:23:43
,在我看来,
getlines(first)似乎没有返回?如果s1上没有输入,还会进行评估吗?
getlines的返回值是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;
}https://stackoverflow.com/questions/59348674
复制相似问题