gpt4 book ai didi

c++ - 多个getline实现

转载 作者:行者123 更新时间:2023-12-02 10:22:48 25 4
gpt4 key购买 nike

我通常使用std::getline来读取控制台输入以应对在线编程挑战,我现在已经解决了很多问题,并且厌倦了编写多个std::getline(std::cin, str1); std::getline(std::cin, str2); std::getline(std::cin, str3);...
因此,我当时使用可变参数模板编写自己的多个阅读行,如果正确,我只需要快速查看一下,因为在我看来getlines(first)未返回? while是否仍会评估s1上是否未输入任何内容?

#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;
}
}

最佳答案

it seems to me that getlines(first) is not returned? Would while still evaluate if nothing is input on 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;
}

关于c++ - 多个getline实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59348674/

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