【问题标题】:Redirecting std::cin directly to std::cout将 std::cin 直接重定向到 std::cout
【发布时间】:2015-08-10 15:55:59
【问题描述】:

关于标准 io 的练习要求我:

从标准输入读取输入并将其写入标准输出。

一个可能的解决方案是:

#include<iostream>
#include<string>

using std::cin; using std::cout;
using std::string;

int main()
{
    string word;
    while (cin >> word)
        cout << word;

    return 0;
}

此示例中的字符串充当缓冲区。如果尝试通过执行以下操作来摆脱缓冲区:

#include<iostream>
using std::cin; using std::cout;

int main()
{
    while (cout << cin)
        ;
    return 0;
}

结果非常不同。当我运行这段代码时,我得到一个无休止的

0x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d300x600d30

在终端上。

为什么会这样?为什么这些程序的行为不同?

【问题讨论】:

  • 你是如何让cout &lt;&lt; cin编译的?
  • 我没有看到这个compiling
  • @scohe001 ideone.com/zRMP7G 完美编译
  • 我在 linux mint debian 版上使用 g++ 4.8.2。我没有使用任何标志,只是(g++ example.cpp -o example)。
  • @scohe001 我只选择“C++”,而你选择“C++14”。不知道这种特殊情况有什么区别。

标签: c++ io


【解决方案1】:

cout &lt;&lt; cin 不会工作你想要的方式。在 C++11 及更高版本中,它甚至无法编译。

您看到了(现已过时的)"safe bool" idiom 的不幸副作用。

在 C++11 之前,std::istreamcould be implicitly converted to a void* to emulate bool semantics.(自 C++11 起,explicit operator bool() const 担任该角色)

因此,代码:

while (cout << cin)

在 C++98 或 C++03 中编译,因为它可以隐式转换为:

while (cout << static_cast<void*>(cin) )

cin 不处于错误状态时,允许此转换生成任何非NULL void*。在您的情况下,它正在生成指针 0x600d30

【讨论】:

  • +1,但告诉一个人如何完成 OP 的预期行为会给你一个 +2(如果我可以投票两次)。
  • @EnricoMariaDeAngelis 我倾向于同意,但在这种情况下,OP 已经在问题中表现出所需的行为,并且只是询问为什么 cout&lt;&lt;cin 会这样做。
【解决方案2】:

在第一个解决方案中,您从 cin 中提取一个字符串并将其重新注入到 cout 中。但是第二种方式,编译器会尝试将cin转换成适合cout注入的值。

您的实现将 cin 转换为指针并重复打印它。我的只是将 cin 转换为 bool 并重复打印 1

但请注意,即使您的第一个版本对多个空格或制表符也不透明,并且可能也不尊重行。我更喜欢:

#include<iostream>
#include <string>


int main()
{
    std::string line;

    while (std::getline(std::cin, line)) {
        std::cout << line << std::endl;
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2012-06-16
    • 1970-01-01
    相关资源
    最近更新 更多