//* data parsing and converting into numbers using sscanf *

#include <iostream> #include <cstring> #include <cstdlib> using namespace std; /* Input: assume that the incoming data has the following format: +OK int_number1 double_number2 or -ERR error message text Goal: if no error then read the two numbers into two variables */ void extract(const char* data, int &n1, double &n2, bool &ok); int main() { char buffer[80]; cin.getline(buffer,80); int val1; double val2; bool extracted; extract(buffer, val1, val2, extracted); if (extracted) { cout << "RECEIVED DATA: " << val1 << " " << val2 << endl; } return(0); } void extract(const char* data, int &num1, double &num2, bool &ok) { ok=false; int bytesread = sscanf(data, "+OK %d %lf", &num1, &num2); // ^^ char array buffer to read from (buffer not damaged) // ^^ text - must be present in input in order to proceed // (anything that does not start with +OK will be ignored) // ^^ instruction what to read // ^^ %magic - each corresponds to one variable to read // %d for decimal int // %lf for double // ^^ variables passed by pointer (with &) // Warning: messing up the variable number and/or their types might result in a program crashing if (bytesread>0) ok=true; // check if reading actually took place }