//* Reading numeric data from a file - parsing with strings and stringstreams *

#include <iostream> #include <fstream> #include <sstream> #include <string> #include <cfloat> using namespace std; int main() { string inName; cout << "Read text from: "; cin >> inName; ifstream inFile; inFile.open(inName.c_str()); if (!inFile.is_open()) { cout << "ERROR: Cannot open " << inName << " file for reading." << endl; return(1); } string SSIDname; cout << "SSID to watch: "; cin >> SSIDname; double sum=0.0; int cnt=0; double max=-DBL_MAX; unsigned line=0; for (;;) { string buffer; getline(inFile, buffer); if (inFile.fail()) { if (inFile.eof()) break; // the failure was caused by the end of file - expected behavior // breaks quits one level of loops - exit the line reading loop - reminder cerr << "ERROR: file reading error - data corrupted, exiting at line number " << line << endl; break; } line++; cout << line << "\r"; if (buffer.size()==0 || buffer[0]=='#') continue; // next line - comment or empty line int p1 = buffer.find("( "); if (p1==string::npos) continue; // next line - this one does not contain SSID data int p2 = buffer.find(" )", p1+2); if (p2==string::npos) continue; // next line - this one does not contain SSID data if (buffer.substr(p1+2, p2-p1-2) != SSIDname) continue; // next line - interested only in a particular SSID int b1 = buffer.find("[ ", p2); if (b1==string::npos) continue; // next line - this one does not contain SNR data int b2 = buffer.find(" ]", b1+2); if (b2==string::npos) continue; // next line - this one does not contain SNR data istringstream inLine(buffer.substr(b1+2, b2-b1-2)); double x, y, z; inLine >> x >> y >> z; if (inLine.fail()) { cerr << "WARNING: Ignored corrupt SNR data in line " << line << endl; continue; // continue goes to the loop control early } sum=sum+x; cnt++; if (max<x) max=x; } inFile.clear(); inFile.close(); if (cnt==0) cout << "No data!" << endl; else { cout << "total: " << line << endl; cout << "data = " << cnt << endl; cout << "avg = " << sum/cnt << endl; cout << "max = " << max << endl; } return(0); } /* Read text from: wifi.txt SSID to watch: MMTEK total: 40481 data = 1888 avg = 27.0524 max = 34 Press any key to continue . . . */