Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将std::istream::sentry与std::istream一起使用_C++_Iostream - Fatal编程技术网

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::istream::sentry用于输入函数内部。解决问题的正确方法是始终检查流是否良好,即读取后读取是否成功:

用于(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";
}