如何使用重定向的标准输入读取文件,即cin(注意:不使用ifstream)
How to read a file using the redirected standard input, i.e. cin(Note:without using ifstream)
加:我通过在VS2013的属性页面中编辑命令argumennts来重定向标准输入。我正在做一个小项目,它要求我在不使用ifstream的情况下读取文件,因为据说:您可以用于此作业的唯一库是iostream,iomanip和string。
您希望将 cin 重定向到文件,为此您需要使用
iOS::RDBUF()
看看这里
还有更多关于 SO 这里和这里
当文件重定向到 stdin(标准输入)时,您应该从 std::cin
stdin(std::istream
的包装器)中读取。 std::basic_ifstream
是std::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"。
相关文章:
- ifstream什么都没读
- ifstream文件在从行中读取时被清除
- std::ifstream::read 不会读取所有 512 字节,并设置 EOF 和失败位
- 将 ifstream 拆分为 n 个流?
- 如何将 std::ifstream 转换为 std::basic_istream<CharT, Traits>&?
- 我在 ifstream input_file(文件名)行中收到错误"no matching function to call";
- 尝试打开 ifstream 时出现"Incomplete type"错误
- 是否可以在没有真实文件的情况下创建 ifstream
- 虽然循环不读取整个 ifstream 文件
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- Ofstream和IFSTREAM有什么区别?
- 如何将QByteArray转换为std::istream或std::ifstream?
- ifstream 跳过数字,只写 0
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 在函数中声明的 ifStream 对象在发布模式下不起作用
- fstream / ifstream / ofstream 对象如何转换为布尔值
- ifstream 尝试读取 9 到 13 之间的无符号字符时非常奇怪的行为
- 尝试在 C++ 中为 ifstream 提供一个变量
- 瓦尔格林德:注意到但未处理的国际奥克特尔;是否有必要处理以及如何找到?
- 如何使用重定向的标准输入读取文件,即cin(注意:不使用ifstream)