C++ 中的流式处理 I/O

Streaming I/O in c++

本文关键字:处理 C++      更新时间:2023-10-16

我正在尝试让这个文件流程序工作,但是当我运行它时,它输出"写入"而不是输出文件。我做错了什么?

#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
  char str[10];
  ifstream b_file ( "ioTest.txt" );
  b_file>> str;
  cout<< str <<"n";
  cin.get(); 
}

标准输入流使用空格作为输入的分隔符。如果您尝试提取到字符串,它将提取每个字符,直到找到空格字符。如果您需要文件的全部内容,这里有几个选项:

while (in >> word)

while (b_file >> word)
{
    std::cout << word;
}

此方法将循环访问输入流中的每个空格分隔标记。

std::getline()

while (std::getline(b_file, line))
{
    std::cout << line;
}

std::getline()检索逐行输入,这意味着它将提取每个字符,直到到达分隔符。默认情况下,分隔符是换行符,但可以指定为第三个参数。

<小时 />

std::istream_iterator<T>

std::copy(std::istream_iterator<std::string>(b_file),
          std::istream_iterator<std::string>(),
          std::ostream_iterator<std::string>(std::cout, "n"));

std::istream_iterator 是一个特殊用途的流迭代器类,旨在"迭代"输入流中 T 类型的令牌。

rdbuf()

std::cout << b_file.rdbuf();

这是更底层的。重载 std::ostream::operator<<() 将流缓冲区指针作为参数,它将直接从缓冲区中提取字符。