打印到控制台的内容:
START(0,0)
GOAL(0,2)
ooox
xxoo
ooox
我希望能够将 START
和 GOAL
点存储为子字符串中的整数,因为打印到控制台上的内容是从外部文件中读取的。
我正在制作一个遍历二维网格的应用程序,其中 x
代表阻塞路径,o
代表畅通无阻。
我尝试使用 .substr()
只获取包含坐标对的字符串部分,并使用 std::stoi()
转换 String 类型变成一个 Int。
void Grid::loadFromFile(const std::string& filename){
std::string line, startPoint, goalPoint;
std::vector<std::string> grid;
int startX, startY, goalX, goalY;
std::ifstream file(filename);
if (!file.is_open()) return;
if (!std::getline(file, line)) return;
if (line.compare(0, 5, "START") != 0) return;
startPoint = line.substr(6,3);
startX = std::stoi(startPoint.substr(1,1));
startY = std::stoi(startPoint.substr(2,2));
if (!std::getline(file, line)) return;
if (line.compare(0, 4, "GOAL") != 0) return;
goalPoint = line.substr(5,3);
goalX = std::stoi(goalPoint.substr(1,1));
goalY = std::stoi(goalPoint.substr(2,2));
test = line.substr(7,1);
while (std::getline(file, line)) {
grid.push_back(line);
}
file.close();
std::cout << "Start: " << startPoint << "\n";
std::cout << "Goal: " << goalPoint << "\n";
std::cout << "Start X: " << startX << "\n";
std::cout << "Start Y: " << startY << "\n";
std::cout << "Goal X: " << goalX << "\n";
std::cout << "Goal Y: " << goalY << std::endl;
}
代码的预期结果是打印正确的 startX/Y
和 goalX/Y
值。
我得到的结果:
Start: 0,0
Goal: 0,2
Start X: 1
Start Y: 162010192
Goal X: 0
Goal Y: 1543563378
我不知道为什么我会得到返回的值,因为它们是随机的,并且对我如何获得这些值毫无意义。
最佳答案
改变
startX = std::stoi(startPoint.substr(1,1));
startY = std::stoi(startPoint.substr(2,2));
到
startX = std::stoi(startPoint.substr(0,1));
startY = std::stoi(startPoint.substr(2,1));
参见 http://www.cplusplus.com/reference/string/string/substr/
substr
有两个参数:子字符串的位置和长度。
这同样适用于您的目标积分。
关于C++如何将子字符串转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54113125/