多条获取线实现
Multiple getline implementation
我通常使用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;
}
相关文章:
- C++如何仅使用MOV在x86上实现发布和获取
- 多条获取线实现
- 在确定有实现的情况下获取HTTP 501未实现
- 在DelphiInterface上实现Dynamic_cast以获取基础对象类的任何方法
- 我如何实现从其基类获取变量的构造函数
- 获取分段错误,用于在 protobuffer 的 C++ 中实现 ByteSize()
- Futex等待/唤醒对实现获取/发布语义吗?
- 如果不在派生类实现中执行此操作,"basic_streambuf"是否会创建自己的获取/放置区域?
- 在实现OpenSceneGraph时在Qt中获取引用问题
- 使用const_cast const-ref getter 实现引用获取器的陷阱
- 获取 QT 代码的普通C++实现
- 我有一个构造函数,但我需要将输出返回到 main.cpp.我无法使用获取字符串功能!!任何想法如何实现这一目标?
- 实现我自己的获取线函数
- 用C++实现多核编程中线程数的获取
- 如何使用套接字实现服务器客户端编程,在套接字中服务器向客户端发送消息而不从客户端获取请求
- 如何实现mysql的DISTINCT关键字,使用线程并行获取不同的值
- 正在获取VARCHAR2类型列:ORA-01460:未实现或请求不合理的转换
- 如何获取/实现类的内置类型成员变量"Uninitialized uses warning"消息?
- 获取释放栅栏的意义不同平台的抽象指令实现
- lldb:无法实现:无法获取变量的值