C++ 在c++;

C++ 在c++;,c++,sfml,C++,Sfml,嗨,我有一个用于映射的类,它正在绘制到屏幕上,但是它只是在窗口左侧垂直向下绘制。我能找出哪里出了问题。任何帮助都将不胜感激。很确定这与draw函数中的for循环有关 void Map::Initialise(const char *filename) { std::ifstream openfile(filename); std::string line; std::vector <int> tempvector; while(!openfil

嗨,我有一个用于映射的类,它正在绘制到屏幕上,但是它只是在窗口左侧垂直向下绘制。我能找出哪里出了问题。任何帮助都将不胜感激。很确定这与draw函数中的for循环有关

void Map::Initialise(const char *filename)
{
     std::ifstream openfile(filename);
     std::string line;
     std::vector <int>  tempvector;
    while(!openfile.eof())
    {
        std::getline(openfile, line);

        for(int i =0; i < line.length(); i++)
        {
            if(line[i] != ' ') // if the value is not a space
            {
                char value[1] = {line[i]}; // store the character into the line variable
                tempvector.push_back(atoi(value)); // then push back the value stored in value into the temp vector
            }
            mapVector.push_back(tempvector); // push back the value of the temp vector into the map vector
            tempvector.clear(); // clear the temp vector readt for the next value
        }
    }
}


void Map::DrawMap(sf::RenderWindow &Window)
{
    sf::Shape rect = sf::Shape::Rectangle(0, 0, BLOCKSIZE, BLOCKSIZE, sf::Color(255, 255, 255, 255));
    sf::Color rectCol;
    sf::Sprite sprite;
    for(int i = 0; i < mapVector.size(); i++)
    {
        for(int j = 0; j < mapVector[i].size(); j++)
        {
            if(mapVector[i][j] == 0)

               rectCol = sf::Color(44, 117, 255);

            else if (mapVector[i][j] == 1)

                rectCol = sf::Color(255, 100, 17);

            rect.SetPosition(j * BLOCKSIZE, i * BLOCKSIZE);
            rect.SetColor(rectCol);
            Window.Draw(rect);

        }
    }
}
void映射::初始化(常量字符*文件名)
{
std::ifstream openfile(文件名);
std::字符串行;
std::向量tempvector;
而(!openfile.eof())
{
std::getline(openfile,line);
对于(int i=0;i
首先,提取
循环时的条件:

while(std::getline(openfile, line))
{
  // ...
}
使用
openfile.eof()
是一个非常糟糕的主意;仅仅因为您还没有到达文件的末尾,并不意味着下一次提取会成功。你只是不知道你是否真的有一行有效的

其次,这不会正常工作:

char value[1] = {line[i]}; // store the character into the line variable
tempvector.push_back(atoi(value));
我明白为什么您使用
char[1]
-您希望将其转换为指针,因为
atoi
采用
const char*
。但是,
atoi
也期望它所指向的数组以null结尾。你的不是。它只是一个
字符

有一种更好的方法可以将数字字符转换为它所代表的整数。所有数字字符的值保证是连续的:

char value = line[i];
tempvector.push_back(value - '0');
现在,真正的问题来了。仅读取一个字符后,将
tempvector
推入
mapVector
。您需要将其移出该行的
for
循环之外:

while(std::getline(openfile, line))
{
    for(int i =0; i < line.length(); i++)
    {
        // ...
    }

    // Moved here
    mapVector.push_back(tempvector); // push back the value of the temp vector into the map vector
    tempvector.clear(); // clear the temp vector readt for the next value
}
while(std::getline(openfile,line)) { 对于(int i=0;i
wow感谢您的反馈。看来我犯了很多错误。我马上把它分类out@TomFlan最后一个问题是它造成的问题(仅在地图左侧绘制):做了更改,但现在它根本没有绘图。我不确定这将如何解决它在左侧绘图的问题,因为这是加载函数。@TomFlan这很奇怪。你能把更新后的代码贴在上面并链接到这里吗?