【问题标题】:c++ Program wont display file in the consolec++程序不会在控制台中显示文件
【发布时间】:2017-02-21 19:51:36
【问题描述】:

我一直在尝试打印文件的内容,但是,它不会打印任何内容,它只会返回 0。我已经检查并仔细检查了我的代码,但找不到任何原因说明它为什么会失败'不工作。这是我的代码示例。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream infile("test.txt");
    string line;
    if(infile.is_open())
    {
      cout << infile.rdbuf();
    }
    else
    {
      cout << "error" << endl;
    }
    infile.close();
    return 0;
}

【问题讨论】:

  • 您从未触发将任何内容读入缓冲区?
  • 我的文件与我的 main.cpp 位于同一文件夹中。我在我的 macbook 上使用 xcode。
  • @πάνταῥεῖ 实际上,为什么原始代码工作? std::cout 是一个std::ostreamstd::ostream::operator&lt;&lt;() 有一个重载,带有指向流缓冲区的指针,这是 dbuf() 返回的内容。
  • 我已经删除了我的答案。使用cout &lt;&lt; infile.rdbuf()应该读取文件。这是关于 Coliru 的一个工作示例(打印源文件,因为我不确定是否还有其他内容可供阅读):coliru.stacked-crooked.com/a/ea7ec2dc80016335

标签: c++ file output


【解决方案1】:

你可以把它读成一个字符串然后打印出来。

#include <string>
#include <fstream>
#include <streambuf>

void func()
{
  // Read into a buffer.
  std::ifstream t("file.txt");
  std::string str;

  t.seekg(0, std::ios::end);   
  str.reserve(t.tellg());
  t.seekg(0, std::ios::beg);

  // Assign to a string.
  str.assign((std::istreambuf_iterator<char>(t)),
            std::istreambuf_iterator<char>());

  // Print out the string to the console.
  std::cout << str << "\n";
}

【讨论】:

  • 谢谢!我一直在尝试做的就是读取文件并在控制台中显示内容。
  • @science1324 当您找到满意答案的帖子时,请将其标记为已回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多