C++ Program help the assignment is to create a program that reads a data file that should contain only integers values and thus should contain only digits, plus or minus signs, and whitespace. the program should print any invalid characters located in the file, and at the end it should print a count of the invalid characters located. (print means show in screen). my current attempt is this:
#include <iostream> #include <fstream> #include <cmath> using namespace std; int main() { ifstream fin; int x; fin.open("invalid.txt"); cout <<"state of fin stream:" << endl<<fin.bad()<<","<<fin.eof()<<","<<fin.fail()<<","<<fin.good()<<endl; if (fin.fail()) { cerr<<"error opening file"<<endl; system("pause"); return -1; } if(fin. fail()) { cerr<<"could not open input file"; } fin>>x; while (!fin.eof()) { cout<<x<<endl; fin>>x; } cout <<"state of fin stream:" << endl<<fin.bad()<<","<<fin.eof()<<","<<fin.fail()<<","<<fin.good()<<endl; cerr <<"Bad data."<<cout<<endl<<" "<<endl; system("pause"); return 0; }
i have no idea how to make the program not just crash and burn when it sees a letter in the file, and no idea how to make it display the invalid characters. Pleas help!
I would try to run through the file once, collecting all the invalid characters (into a vector or array of characters), and then print them all out at the end. This would involve: making a storage vector, running through the file finding invalid entries, closing the file, printing out the elements of the array, and then printing out the size of the vector.
Join our real-time social learning platform and learn together with your friends!