简体   繁体   English

在C ++中,有没有一种可移植的方法将stdin重定向到字符串?

[英]Is there a portable way to redirect stdin to string in C++?

Is it possible in C++ to redirect stdin to string in C++? 在C ++中是否可以将stdin重定向到C ++中的字符串?

Using freopen I can redirect stdin to file, so both scanf and cin will use a content of that file. 使用freopen,我可以将stdin重定向到文件,因此scanf和cin都将使用该文件的内容。 Using manipulations with stringstream and cin.rdbuf() I can redirect cin to that string, so any call to cin will work with my string. 通过使用stringstream和cin.rdbuf()进行操作,我可以将cin重定向到该字符串,因此对cin的任何调用都可以与我的字符串一起使用。 BUT scanf will continue to work with previous input stream. 但是scanf将继续与先前的输入流一起使用。 I guess it is possible to do with Unix's pipes but it's not available under Windows. 我想这可能与Unix的管道有关,但在Windows下不可用。

Is it possible to solve this in a portable way? 是否可以通过便携式方式解决此问题?

This isn't the best way to do it, but you can make it work with something like this: 这不是最好的方法,但是您可以使它与以下内容一起工作:

// warning - has side effects (sets noskipws) but we don't care (its an example)
ostream& operator<< (ostream& out, istream& in)
{
    in >> noskipws;
    char c;
    in >> c;

    while (in)
    {
        out << c;
        in >> c;
    }

    return out;
}

int main()
{
    ostringstream inputstr;
    inputstr << cin;

    inputstr.str(); // contains all data from stdin
    return;
}

Assuming both the C and C++ standard streams are synchronized, the following should work: 假设C和C ++标准流都已同步,则以下内容应该起作用:

class save_buffer
{
public:
    save_buffer(std::ios& str) :
        my_str(str),
        m_sbuf(str.rdbuf())
    { }

    ~save_buffer()
    {
        m_str.rdbuf(m_sbuf);
    }
private:
    std::ios& m_str;
    std::streambuf* m_sbuf;
};

int main()
{
    std::istringstream buf;

    save_buffer sb(std::cin);
    std::cin.rdbuf(buf.rdbuf());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM