//* data parsing and converting into numbers using atoi/atof - char array notation *

#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; if (data[0]=='+') { // dillema: can we just check for '+' and '-' and assume that it is +OK or -ERR? // answer: it depends on what is the source of ouf data (human or other program) // and on how robust, fast, and big our program needs to be. int i=0; // start at the beginning of the array while (data[i]!=0 && data[i]!=' ') i++; // move until either end of string or while space while (data[i]!=0 && data[i]==' ') i++; // move until either end of string or white space ended if(data[i]!=0) { num1=atoi(&data[i]); while (data[i]!=0 && data[i]!=' ') i++; // move until either end of string or while space while (data[i]!=0 && data[i]==' ') i++; // move until either end of string or white space ended if(data[i]!=0) { num2=atof(&data[i]); ok=true; } } } else if (data[0]=='-') { } else { cout << "WARNING: data not in expected format!" << endl; } }