使用ifstream进行简单的.text文件读取

时间:2013-01-29 03:06:18

标签: c++ file 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。通过使用文本文件的绝对文件名来解决问题。

1 个答案:

答案 0 :(得分:0)

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

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

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