C++ 如何从 ifstream 和 getline() 获取子字符串
C++ How to get substring from ifstream and getline()
打印到控制台的内容:
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...
}
或者,如果您知道第一行总是START
和GOAL
:
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 循环范围之外使用的方法(可能是字符串数组)。
希望对:)有所帮助
相关文章:
- 获取字符串的长度并将其分配给数组
- 调用CreateProcess()并获取字符串的返回值
- 你如何从 Boost Spirit X3 词法解析器中获取字符串?
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 如何从输入中获取字符串向量?
- 如何获取字符串输入n次?
- property_tree获取字符串形式的数组值
- 使用 ctypes 和 wchar_t 时如何从 C++ 获取字符串到 python?
- 获取字符串大小的各种方法之间的比较
- 方法获取字符串
- 在getline()之后获取字符串
- 为什么我的拆卸C 代码使用指令指针和偏移来获取字符串文字
- 无法使用 Poco 获取字符串的路径
- 如何在qtablewidget中获取字符串的行号
- 如何获取字符串和字节进行比较
- 恒定字符阵列的获取字符串长度函数(strlen)不是恒定表达式
- 我需要创建一个函数来获取字符串中的这些数字
- 如何从地址获取字符串?
- 为什么即使尚未初始化,获取字符串[0]也是有效的?
- 获取C++字符串的位