1

所以我有一个名为“maze.txt”的文本文件,如下所示:

###############
Sacbifnsdfweovw
###############

我想检查左下角的字母是否是“S”,然后检查右边的字母是否是字母字符。然后,我会继续检查前一个字母后面的字符是否是字母字符。这些字母将存储在我的矢量“路径”中。最后,我将打印以筛选我们经历过的每个字母。但是出于某种原因,对于上面的那一大块字母,屏幕只打印出“S”和“a”,而没有其他任何内容。怎么了?这是我的代码:

int main()
{
    ifstream file("maze.txt");
    if (file) {
        vector<char> vec(istreambuf_iterator<char>(file), (istreambuf_iterator<char>())); // Imports characters from file
        vector<char> path;                      // Declares path as the vector storing the characters from the file
        int x = 17;                             // Declaring x as 17 so I can use it with recursion below
        char entrance = vec.at(16);             // 'S', the entrance to the maze
        char firstsquare = vec.at(x);           // For the first walkable square next to the entrance

        // Check that the entrance really has 'S'
        if (entrance == 'S')                    
        { 
            path.push_back(entrance);           // Store 'S' into vector 'path'
        }

        // Check if the first path is an alphabetical character and thus walkable
        if (isalpha(firstsquare))               
        {
            path.push_back(firstsquare);        // Store that character into vector 'path'
            isalpha(vec.at(x++));               // Recurse 'isalpha' to the next adajcent square of the maze;
        }                                       // checking next character

        cout << "Path is: ";                    // Printing to screen the first part of our statement

        // This loop to print to the screen all the contents of the vector 'path'.
        for(vector<char>::const_iterator i = path.begin(); i != path.end(); ++i)  // 
        {
        std::cout << *i << ' ';
        }

        cout << endl;
        system ("pause");                       // Keeps the black box that pops up, open, so we can see results.
        return 0;
        }
}

提前致谢!顺便说一句,我是 C++ 新手。

4

1 回答 1

3

由于这看起来像是一个学习项目(家庭作业、自学等),我只会给出提示。

我认为这一行(尤其是评论)表明了问题:

isalpha(vec.at(x++)); // Recurse 'isalpha' to the next adajcent square of the maze;

你没有“递归”任何东西,你忽略了 isalpha 的结果。您只是在确定下一个字符是否按字母顺序排列,然后什么也不做,只有那个字符。

于 2012-05-25T17:34:50.603 回答