简单.txt 使用 ifstream 读取文件



对于我一整天都无法弄清楚的事情来说,这可能是一个基本问题。下面是一段C++代码:

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。此问题已通过改用文本文件的绝对文件名得到解决。

而不是file >> gridWidth >> gridHeight >> nKeys;这样做:

while(file >> gridWidth && file >> gridHeight && file >> nKeys)

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

最新更新