【问题标题】:Combine input and output streams合并输入和输出流
【发布时间】:2017-03-08 07:00:51
【问题描述】:

我想将输入和输出流合并到输出流中。 我的意思是,如果这是我的代码:

int num;
string str;
cout << "string: ";
cin >> str;
cout << "num: ";
cin >> num;
cout << "num is " << num << " str is " << str;

我将输入流重定向到一个txt文件包含:

嘿1

我的输出流将包含:

string: hey
num: 1
num is 1 str i hey

安装于:

string: num: num is 1 str is hey

我不想在收到输入后计算 cin 中的每个变量。我希望它是自动的。

【问题讨论】:

  • 输出一些换行符?
  • @πάνταῥεῖ 输出也不包含输入值,而不仅仅是新行。
  • “我希望它是自动的。”所以你迷路了。
  • @πάνταῥεῖ in c# 我继承了输入流类并覆盖了 ReadLine 方法并在返回值之前添加了打印。我不能在 C++ 中做类似的事情吗?

标签: c++ redirect input output


【解决方案1】:

为包装类重载 std::istream::operator >> 并做你喜欢的事:

// Example program
#include <istream>
#include <string>
#include <vector>

class AutoCinToCoutReader {
    public: 
        inline void write(const std::string& in) { std::cout << in << std::endl; }
};

std::istream& operator >> (std::istream& is, AutoCinToCoutReader& dt)  
{  
    std::string in;
    is >> in;
    dt.write(in);

    return is;  
}  

void read(const std::string& what, AutoCinToCoutReader& rd) {

    std::cout << what << ": ";
    std::cin  >> rd;
}

int main()
{
    AutoCinToCoutReader rd;

    std::vector<std::string> fields = { "Test1", "Test2" };

    for(const std::string& field : fields) {
        read(field, rd);
    }
}

更新:

我能提供的最小的东西是:

// Example program
#include <string>
#include <vector>
#include <iostream>
#include <istream>
#include <ostream>

std::istream& operator >> (std::istream& is, std::ostream& os) {
    std::string in;
    is >> in;
    os << in << std::endl;
    return is;
}

void read(const std::string& what) {

    std::cout << what << ": ";
    std::cin  >> std::cout;
}

int main()
{

    std::vector<std::string> fields = { "Test1", "Test2" };

    for(const std::string& field : fields) {
        read(field);
    }
}

您不能立即从 cin 写入 cout。无论如何,您需要解决它。见更新后的算子,存入cin后直接输出到cout。

【讨论】:

  • 我不想要一个包装类,我正在为一个函数编写测试,该函数应该在不更改 cin 和 cout 的使用的情况下编写。
  • 查看更新...顺便说一句,我只是调用 std::cin、std::cout... 所以我不会更改它们的用途.. 就在我使用它们的地方...
猜你喜欢
  • 1970-01-01
  • 2011-04-25
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多