我试图让这个文件流程序工作,但是当我运行它时,它只输出“Writing”而不是输出文件。我做错了什么?
#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<<()
的过载将流缓冲区指针作为参数,它将直接从缓冲区中提取字符。
关于c++ - C++ 中的流式 I/O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666523/