zoukankan      html  css  js  c++  java
  • c++ cin cout重定向

    在C语言中,方法比较简单。使用函数freopen():

    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);

    这样就把标准输入重定向到了data.in文件,标准输出重定向到了data.out文件。

    这两句代码之后,scanf函数就会从data.in文件里读,而printf函数就会输出到data.out文件里了。

    C++中,对流重定向有两个重载函数:

    streambuf* rdbuf () const;
    streambuf* rdbuf (streambuf *)


    streambuf *backup;
    ifstream fin;
    fin.open("data.in");
    backup = cin.rdbuf(); // back up cin's streambuf
    cin.rdbuf(fin.rdbuf()); // assign file's streambuf to cin
    // ... cin will read from file
    cin.rdbuf(backup); // restore cin's original streambuf

    注意最后我们使用了cin.rdbuf(backup)把cin又重定向回了控制台

    然而,如果用C语言实现同样的功能就不那么优雅了。

    因为标准控制台设备文件的名字是与操作系统相关的。

    在Dos/Windows中,名字是con

    freopen("con", "r", stdin);

    在Linux中,控制台设备是/dev/console

    freopen("/dev/console", "r", stdin);

    另外,在类unix系统中,也可以使用dup系统调用来预先复制一份原始的stdin句柄。

    stringstream
    标准头文件<sstream>定义了一种称为stringstream的类型,该类型允许将字符串视为流,从而允许以与在cin和cout上执行的方式相同的方式从字符串中提取或插入字符串。

    此功能对于将字符串以及数值之间的相互转换非常有用,即,可以间接的从标准输入中获取数值。比如字符串到数值的转换

    stringstream快速实现String和int之间的转换

    #include <iostream>
    #include <string>
    #include <sstream>
    using namespace std;
    int string2int(string str){
    int num;
    stringstream sstream;
    sstream << str;
    sstream >> num;
    return num;
    }
    string int2string(int num){
    string re;
    stringstream sstream;
    sstream << num;
    return sstream.str();
    }

  • 相关阅读:
    《领域驱动设计的原则与实践》读书笔记(一)
    asp.net identity UserSecurityStamp 的作用
    Python Django Apache配置
    SQL语句优化(转载)
    【转】性能测试,影响 TPS 的一些因素
    【转】接口测试总结
    【转】两款 Web 前端性能测试工具
    【转】工作中使用Trepn Power Profiler的应用总结
    【转】nGrinder 简易使用教程
    Http协议状态码总结
  • 原文地址:https://www.cnblogs.com/youxin/p/15768584.html
Copyright © 2011-2022 走看看