C++ 将std::istream::sentry与std::istream一起使用
考虑以下简单程序,它将输入拆分为空白,并每行打印一个非空白标记:C++ 将std::istream::sentry与std::istream一起使用,c++,iostream,C++,Iostream,考虑以下简单程序,它将输入拆分为空白,并每行打印一个非空白标记: #include <iostream> int main(int argc, char* argv[]) { while (std::cin) { std::string s; std::cin >> s; std::cout << "-" << s <
#include <iostream>
int main(int argc, char* argv[])
{
while (std::cin)
{
std::string s;
std::cin >> s;
std::cout << "-" << s << "-\n";
}
return 0;
}
我们可以通过将输出行设置为条件来处理这个问题!s、 empty()
然而,还有另一种选择。我们可以更换以下线路:
while (std::cin)
与:
sentry对象(通常由操作符>>
在内部使用)的作用是使用空格,然后检查EOF或其他流状态:
[begin]
< a b c
> -a-
> -b-
> -c-
< (^D)
[end]
[开始]
-a-
>-b-
>-c-
<(^D)
[完]
我的问题有三个:
- 是否有任何原因导致此构造无法按预期工作
- 它已经习惯了吗
- 若否,原因为何
用于(std::string s;std::cin>>s;){
std::难道这是对传统的“为什么我的而(!strm.eof())
循环不工作?”问题的一种创造性的扭曲吗?尽管最终答案是相同的。
while (std::istream::sentry(std::cin))
[begin]
< a b c
> -a-
> -b-
> -c-
< (^D)
[end]
for (std::string s; std::cin >> s; ) {
std::cout << '-' << s << "-\n";
}