如何使用重定向的标准输入读取文件,即cin(注意:不使用ifstream)

How to read a file using the redirected standard input, i.e. cin(Note:without using ifstream)

本文关键字:注意 ifstream cin 重定向 何使用 标准输入 读取 文件      更新时间:2023-10-16

加:我通过在VS2013的属性页面中编辑命令argumennts来重定向标准输入。我正在做一个小项目,它要求我在不使用ifstream的情况下读取文件,因为据说:您可以用于此作业的唯一库是iostream,iomanip和string。

您希望将 cin 重定向到文件,为此您需要使用

iOS::RDBUF()

看看这里

还有更多关于 SO 这里和这里

当文件重定向到 stdin(标准输入)时,您应该从 std::cin stdin(std::istream 的包装器)中读取。 std::basic_ifstreamstd::basic_istream的一个子类,所以大多数读取函数在它们中都可用,你应该熟悉它们。这意味着您可以使用:

  • std::getline逐行读取文件:

    std::string s;
    while(std::getline(std::cin, s)) {
        std::cout << s << std::endl;
    }
    
  • operator >>读取由空格字符分隔的字段:

    while(std::cin) {
        std::string s;
        std::cin >> s;
        std::cout << s << std::endl;
    }
    

在此处查看其运算符和功能的完整列表: http://en.cppreference.com/w/cpp/io/basic_istream

您可以使用"freopen"函数。例:

freopen("input.txt","r",stdin).

这意味着您读取文件"input.txt"并将其内容保存到"stdin"。现在,您可以使用"cin"。