从文件填充数组将不起作用

时间:2014-01-28 18:51:00

标签: c++ arrays file io

我制作了一个'Map'数组,我试图从'map'文件中填充它。在创建时,我将值'0'分配给数组的每个元素,但'Map'文件包含以下内容:

MAP:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

我使用'loadMap()'

加载地图

loadMap():

void room::loadMap()
{
    int x=0;
    int y=0;
    string line;
    ifstream mapFile(NAME + "_MAP.txt");

    while(!mapFile.eof())
    {
        for(int i=0; i<cellsY; i++)
        {
            getline(mapFile,line,'\n');

            for(int j=0; j<cellsX; j++)
            {
                getline(mapFile,line,' ');
                map[(cellsX*j) + cellsY] = atoi(line.c_str());
            };
        };
    }

    y = 10;
    x = 15;
    for(int i=0; i<y; i++)
        {
            cout << endl;
            for(int j=0; j<x; j++)
            {
                cout << map[(x*j) + y];
            };
        };
}

在此示例中,元素仍然被指定为“0”,但我正在尝试模仿地图文件布局。

2 个答案:

答案 0 :(得分:0)

对于初学者,你从不测试任何输入是否有效,也没有 开放成功了。然后,在外循环中,您阅读 文件中的一行,然后扔掉,然后再读 在内循环中。你对指数的计算是错误的。

您可能正在寻找的是:

std::ifstream mapFile(...);
if ( !mapFile.is_open() ) {
    //  Error handling...
}
for ( int i = 0; mapFile && i != cellsY; ++ i ) {
    std::string line;
    if ( std::getline( mapFile, line ) ) {
        std::istringstream text( line );
        for ( int j = 0; j != cellsX && text >> map[cells X * i + j]; ++ j ) {
        }
        if ( j != cellsX ) {
            //  Error: missing elements in line
        }
        text >> std::ws;
        if ( text && text.get() != EOF ) {
            //  Error: garbage at end of line
        }
    }
}

对于错误处理,最简单的只是输出一个 适当的错误消息并继续,注意错误,所以你 可以在最后返回某种错误代码。

答案 1 :(得分:0)

我认为这就是你要找的东西。

void room::loadMap()
{
   int x=0;
   int y=0;
   ifstream mapFile(NAME + "_MAP.txt");

   for(int i=0; i<cellsY; i++)
   {
      for(int j=0; j<cellsX; j++)
      {
         int v;
         mapFile >> v;
         if ( mapFile.eof() )
         {
            break;
         }
         map[(cellsX*j) + cellsY] = v;
      }
   }

   y = 10;
   x = 15;
   for(int i=0; i<y; i++)
   {
      cout << endl;
      for(int j=0; j<x; j++)
      {
         cout << map[(x*j) + y];
      };
   };
}
相关问题