【问题标题】:Simple .txt File-Reading with ifstream使用 ifstream 进行简单的 .txt 文件读取
【发布时间】:2013-01-29 03:06:18
【问题描述】:

对于我一整天都无法弄清楚的问题,这可能是一个基本问题。这是 C++ 的 sn-p 代码:

Escape::Escape(std::string filename)
{
   std::ifstream file;
   file.open(filename.c_str());
   if (file.is_open()) {
      file >> gridWidth >> gridHeight >> nKeys;
      std::cout << "gridWidth = " << gridWidth << std::endl;
      std::cout << "gridHeight = " << gridHeight << std::endl;
      std::cout << "nKeys = " << nKeys << std::endl;
      /* irrelevant code below */

基本上,我希望这段代码读取文本文件的前三个整数并将它们保存到变量 gridWidth、gridHeight 和 nKeys 中。这些是名为“Escape”的类的私有整数。以下是文本文件的前几行:

8
8
1
BUL--/EUR--/BUL--/BU---/BU---/BU---/BU---/BUR--/
(more text below)

下面是这段代码的一些示例输出:

gridWidth = 107764358
gridHeight = -991553646
nKeys = 0

多次运行此代码时,gridWidthgridHeight 始终是垃圾,nKeys 始终为 0。关于我做错了什么有什么想法吗?

编辑:问题出在我传递给file.open() 的文件名上。我传入了相对文件名,虽然可以打开,但不能链接到 ifstream。该问题已通过使用文本文件的绝对文件名解决。

【问题讨论】:

  • 通过管道将文件传输到cout 非常快

标签: c++ file ifstream


【解决方案1】:

代替file &gt;&gt; gridWidth &gt;&gt; gridHeight &gt;&gt; nKeys; 这样做:

while(file &gt;&gt; gridWidth &amp;&amp; file &gt;&gt; gridHeight &amp;&amp; file &gt;&gt; nKeys)

这比将结果存储在字符串中然后必须进行转换要好。

【讨论】:

  • 我也试过了,结果还是一样。 gridWidth 是垃圾,gridHeight 是垃圾,nKeys 是 0。我承认这是更好的样式,这是我将尝试合并的解决方案。这些错误是否有其他原因?谢谢
  • @BanjoKaJoey 我制作了一个示例文本文件并编辑了我的答案,我认为这是由于您的循环while(file.is_open())
猜你喜欢
  • 2021-03-22
  • 2017-06-28
  • 2010-12-09
  • 1970-01-01
  • 2021-06-10
  • 2011-12-13
  • 1970-01-01
相关资源
最近更新 更多