简体   繁体   English

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

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

Plus: I redirected standard input by editing the command argumennts in property pages in VS2013. 另外:我通过在VS2013的属性页中编辑命令参数来重定向标准输入。 I'm doing a small project and it requires I read a file without using the ifstream cause it's said: The only libraries you may use for this assignment are iostream, iomanip, and string. 我正在做一个小项目,它要求我不使用ifstream即可读取文件,原因是:可以用于此分配的唯一库是iostream,iomanip和string。

You want to redirect cin to a file and for that you need to set the stream buffer associated with cin using 您想将cin重定向到一个文件,为此您需要使用以下命令设置与cin关联的流缓冲区

ios::rdbuf() ios :: rdbuf()

Take a look here 在这里看看

and a couple more on SO here and here 还有更多关于这里这里的信息

You can use "freopen" functionn. 您可以使用“ freopen”功能。 Example: 例:

freopen("input.txt","r",stdin). freopen(“ input.txt”,“ r”,stdin)。

That means you read a file "input.txt" and save it's contents to "stdin". 这意味着您读取了文件“ input.txt”并将其内容保存到“ stdin”。 Now, you can use "cin". 现在,您可以使用“ cin”。

When file is redirected to stdin (standard input), you should read from std::cin (instance of std::istream ) which is wrapper around stdin. 当文件重定向到stdin (标准输入)时,您应该从std::cinstd::istream实例)中读取,该文件是stdin的包装。 std::basic_ifstream is a subclass of std::basic_istream , so most reading functions are available in both of them and you should familiar with them. std::basic_ifstream是子类std::basic_istream ,所以大部分的阅读功能两者都可以,你应该熟悉他们。 Which means that you can use: 这意味着您可以使用:

  • std::getline to read file line by line: std::getline逐行读取文件:

     std::string s; while(std::getline(std::cin, s)) { std::cout << s << std::endl; } 
  • operator >> to read fields delimited by space character: operator >>读取由空格分隔的字段:

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

Check out full list of its operators and functions here: http://en.cppreference.com/w/cpp/io/basic_istream 在此处查看其操作符和功能的完整列表: http : //en.cppreference.com/w/cpp/io/basic_istream

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

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