为什么rdbuf()不打印任何内容
Why does rdbuf() not print anything?
在以下示例中,
ifstream myFile;
myFile.open("example.txt", ios::binary);
cout << myFile.rdbuf() << endl;
myFile.close();
文件的内容将全部打印在一行中。你也可以这样做:
ifstream myFile;
myFile.open("example.txt", ios::binary);
unsigned char character = myFile.get();
while(myFile){
cout << "one character = ";
cout << character;
character = myFile.get(); //gets each individual character, 1 at a time
}
myFile.close();
它将打印文件的内容,一次打印一个字符。但是,如果您尝试一个接一个地(按任何顺序)执行这些方法,那么实际上只有一个方法会打印任何内容。有人能解释一下为什么在下面的例子中,对rdbuf()
的调用不会打印文件的内容吗?
ifstream myFile;
myFile.open("example.txt", ios::binary);
unsigned char character = myFile.get();
while(myFile){
cout << "one character = ";
cout << character;
character = myFile.get(); //gets each individual character, 1 at a time
}
cout << myFile.rdbuf() << endl;
myFile.close();
谢谢!
从流中读取时,读取位置会递增。逐个字符读取整个文件后,读取位置位于文件末尾。在这种情况下,rdbuf()
(读取缓冲器)没有其他感兴趣的内容。
如果要使用rdbuf()
再次打印文件,可以在尝试打印之前使用myFile.seekg(0, std::ios::beg);
设置读取位置。在这个特定的示例中,可能已经设置了错误位,因此在移动读取指针之前,您可能需要执行myFile.clear()
。
相关文章:
- 打印时有二叉树问题.用户输入不打印任何内容
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- cout 不打印任何内容到控制台
- 为什么字符串没有更新并且最终没有打印任何内容
- 我如何处理 TMP 以避免打印任何东西
- 是否有任何内置的哈希图函数来处理 c++ 中的值输入?
- 泛型函数反向打印任何矢量,编译器出错
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- Cout 一个字符串可以打印任何内容到屏幕上
- "cout<<count<<endl;"没有打印任何内容
- C++ 中是否有任何内置阶乘函数?
- 为什么循环迭代不打印任何东西?
- 函数不打印任何 c++
- 下面的代码没有打印任何东西
- 我的 c++ 程序中的字符数组不会打印任何内容
- 如果否则错误:如何使其打印任何数字
- 在 C++ 中声明向量后无法打印任何内容
- 在模板功能中打印任何结构
- 如果找不到解决方案,我如何留下递归循环,而不会打印任何东西
- 是否有任何内置函数可以告诉编译器分支是否可预测