//* Reading complex data from a file - parsing with char[] and with atoi or atof *

#include <iostream> #include <fstream> #include <cstdlib> #include <cstring> #include <cfloat> using namespace std; int main() { char inName[80]; cout << "Read text from: "; cin >> inName; ifstream inFile; inFile.open(inName); if (!inFile.is_open()) { cout << "ERROR: Cannot open " << inName << " file for reading." << endl; return(1); } char SSIDname[16]; cout << "SSID to watch: "; cin >> SSIDname; int SSIDlen=strlen(SSIDname); double sum=0.0; int cnt=0; double max=-DBL_MAX; unsigned line=0; for (;;) { char buffer[1024]; inFile.getline(buffer, 1024); 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[0]=='#') continue; // next line - comment, empty line would still have buffer[0] defined as =='\0' int p1 = 1; while (buffer[p1]!='\0' && buffer[p1]!='(') p1++; if (buffer[p1]=='\0') continue; // next line - this one does not contain SSID data if (strncmp(&buffer[p1+2], SSIDname, SSIDlen) !=0 ) continue; // next line - interested only in a particular SSID // note that we need to start comparing the part of buffer that starts at p1+2 instead of at 0 // note that we need to enforce comparing only up to SSIDlen and buffer has more data after the name int b1 = p1; while (buffer[b1]!='\0' && buffer[b1]!='[') b1++; if (buffer[b1]=='\0') continue; // next line - this one does not contain SNR data double x, y, z; int s1=b1+1; // skip the '[' x = atof(&buffer[s1]); // note initial space and any more data after the number is ignored // note: use atoi if parsing an integer number s1++; // skip the initial one space while (buffer[s1]!='\0' && buffer[s1]!=' ') s1++; if (buffer[s1]=='\0') continue; // next line - this one does not contain SNR data y = atof(&buffer[s1]); s1++; // skip the initial one space while (buffer[s1]!='\0' && buffer[s1]!=' ') s1++; if (buffer[s1]=='\0') continue; // next line - this one does not contain SNR data z = atof(&buffer[s1]); 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 . . . */