C++ 如何从 ifstream 和 getline() 获取子字符串

C++ How to get substring from ifstream and getline()

本文关键字:获取 字符串 getline ifstream C++      更新时间:2023-10-16

打印到控制台的内容:

START(0,0)
GOAL(0,2)
ooox
xxoo
ooox

我希望能够获得 START 和 GOAL 点的子字符串,不包括括号,只包括坐标对。我还想将它们存储为变量,因为我想添加验证 START 或 GOAL 点是否超出网格的范围。

我正在尝试制作一个应用程序来遍历 2D 网格,其中"x"表示阻塞的路径,"o"表示未阻塞的路径。

起点始终从网格的左下角开始,如下所示:

(0,2)(1,2)(2,2)(3,2)
(0,1)(1,1)(2,1)(3,1)
(0,0)(1,0)(2,0)(3,0)

我尝试使用.substr()方法作为我想存储值的起点和终点,但它不会在控制台中打印出任何内容。

void Grid::loadFromFile(const std::string& filename){
    std::string line;
    std::ifstream file(filename);
    file.open(filename);
    // Reads the file line by line and outputs each line
    while(std::getline(file, line)) {
        std::cout << line << std::endl;
    }
        std::string startPoint, goalPoint;
        startPoint = line.substr(6,3);
        std::cout << startPoint << std::endl;
        file.close();
    }

我希望std::cout << startPoint << std::endl;将子字符串打印到控制台中,但它只是读取文件并打印其中的任何内容,没有其他内容。

问题是您首先读取文件的所有行,然后仅解析已读取的最后一行,请求超出范围的起始索引。

您需要在读取循环内移动解析:

void Grid::loadFromFile(const std::string& filename)
{
    std::ifstream file(filename);
    if (!file.is_open()) return;
    std::string line, startPoint, goalPoint;
    std::vector<std::string> grid;
    while (std::getline(file, line))
    {
        if (line.compare(0, 5, "START") == 0)
            startPoint = line.substr(6,3);
        else if (line.compare(0, 4, "GOAL") == 0)
            goalPoint = line.substr(5,3);
        else
            grid.push_back(line);
    }
    file.close();
    std::cout << startPoint << std::endl;
    std::cout << goalPoint << std::endl;
    // process grid as needed...
}

或者,如果您知道第一行总是STARTGOAL

void Grid::loadFromFile(const std::string& filename)
{
    std::ifstream file(filename);
    if (!file.is_open()) return;
    std::string line, startPoint, goalPoint;
    std::vector<std::string> grid;
    if (!std::getline(file, line)) return;
    if (line.compare(0, 5, "START") != 0) return;
    startPoint = line.substr(6,3);
    if (!std::getline(file, line)) return;
    if (line.compare(0, 4, "GOAL") != 0) return;
    goalPoint = line.substr(5,3);
    while (std::getline(file, line))
        grid.push_back(line);
    file.close();
    std::cout << startPoint << std::endl;
    std::cout << goalPoint << std::endl;
    // process grid as needed...
}
我相信

getline 只将文件中的数据存储到 for 循环中文件每一行的字符串行中,直到它达到 null。

所以在 for 循环线之后基本上 = null。

您需要一种读取文件的替代方法或一种存储数据以在 for 循环范围之外使用的方法(可能是字符串数组)。

希望对:)有所帮助