首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多个getline实现

多个getline实现
EN

Stack Overflow用户
提问于 2019-12-15 22:36:25
回答 1查看 59关注 0票数 1

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

因此,我使用各种模板编写了自己的多条读行,如果这是正确的,我只需要快速检查一下,因为在我看来,getlines(first)似乎没有返回?如果s1上没有输入,while还会评估吗?

代码语言:javascript
复制
#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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-15 23:23:43

,在我看来,getlines(first)似乎没有返回?如果s1上没有输入,还会进行评估吗?

getlines的返回值是istream & ..。而且它确实没有被使用。不过,这并不重要,因为您也有对该流(std::cin)的引用。因此,即使由于EOF或其他条件不能设置s1,也会在std::cin中设置相应的标志,因此,一旦您返回它(在结束时会这样做),就会在while循环的条件下进行测试。

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

代码语言:javascript
复制
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...);
}

顺便说一句,我想出的是:

代码语言:javascript
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59348674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档