I am trying to parse through a gcode and I want to extract only the x & y coordinates of G1 from each line
GCODE EXAMPLE
G1 X123.456 Y125.425 Z34.321
I tried the basic getline()
function but it prints the whole line, don't understand how to add filters to the getline()
to just extract only x & y numerical values and only for lines with G1 on start.
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <fstream>
using std::cout; using std::cerr;
using std::endl; using std::string;
using std::ifstream; using std::vector;
int main()
{
string filename("test1.gcode");
vector<string> lines;
string line;
ifstream input_file(filename);
if (!input_file.is_open()) {
cerr << "Could not open the file - '"
<< filename << "'" << endl;
return EXIT_FAILURE;
}
while (getline(input_file, line)){
lines.push_back(line);
}
for (const auto &i : lines)
cout << i << endl;
input_file.close();
return EXIT_SUCCESS;
}
You cannot add filters to getline()
. It will always return the complete next line in the input.
What you can do is parse this line yourself, and extract the values that you need.
This is can be done in multiple ways. One of them is demonstrated below.
I used std::string::find
to get an offset for the character 'X'/'Y' marking the x/y coordinates.
Then I used std::atof
to convert the relevant part of the line to a double
value.
I also used std::string::find
to check whether the line starts with the required prefix for this command.
#include <string>
#include <iostream>
#include <cstdlib>
int main()
{
std::string line = "G1 X123.456 Y125.425 Z34.321";
if (line.find("G1") == 0)
{
size_t xpos = line.find('X');
if (xpos == std::string::npos) { /* handle error */ }
double x = std::atof(line.data() + xpos + 1); // skip over the 'X'
size_t ypos = line.find('Y');
if (ypos == std::string::npos) { /* handle error */ }
double y = std::atof(line.data() + ypos + 1); // skip over the 'Y'
std::cout << "X: " << x << ", Y: " << y << std::endl;
}
}
Output:
X: 123.456, Y: 125.425