//* Reading numeric data from a file - direct stream parsing *

#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 (;;) { char c; c=inFile.peek(); if (inFile.fail()) break; // end of file or other serious reading error line++; cout << line << "\r"; if (c=='#') { inFile.ignore(1024,'\n'); continue; } while( (! inFile.fail()) && c!='(') inFile.get(c); // "eat" until '(' including it inFile.get(c); // eat space afterwards string SSIDcurrent; inFile >> SSIDcurrent; if (inFile.fail()) break; // end of file or other serious reading error if (SSIDcurrent != SSIDname) continue; // next line - interested only in a particular SSID while( (! inFile.fail()) && c!='[') inFile.get(c); // "eat" until '[' including it inFile.get(c); // eat space afterwards double x, y, z; inFile >> x >> y >> z; if (inFile.fail()) { cerr << "WARNING: Ignored corrupt SNR data in line " << line << endl; inFile.clear(); // clear the error status so that we can continue with reading inFile.ignore(1024,'\n'); continue; // continue with the next line } inFile.ignore(1024,'\n'); // ignoring the reminder of the line so that next iteration starts with a new line // if that was the very last line without '\n' then we will handle end of file after attempting inFile.peek() 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: 156249 data = 1888 avg = 27.0524 max = 34 Press any key to continue . . . */