// Zeinalipour-Yazti Demetrios // csyiazti // cs10xx - // Lab Sec#24,29,30 // lab7 #include #include #include #include #include using namespace std; /* This program reads in integers from a file chosen by the user at runtime. * It then prints out the number and each individual digit of that number. * We assume that all the numbers in the file are positive values less than * 10,000. The digits line up nicely. */ // the length of the largest number (e.g 1020 => 4) const int MAX_NUMBER = 4; /* this function takes by reference an ifstream. It basically * makes sure that the user enters the appropriate output * file, gets a pointer to it and quits. */ void getFileStream(ifstream& infilestream) { string filename; // repeat the loop until the user enters the correct filename while (true) { /* get the filename */ cout << "Give me the name of the file: " ; cin >> filename; cout << "\nOpening \'" << filename << "\'..."; /* open file in read mode */ infilestream.open(filename.c_str(), ios::in); // if the file was opened succesful then break this loop // else display error message and let him try again if (infilestream) { cout << "done\n"; break; } else { cout << "failed\n"; cerr << "File could not be opened\n" << endl; infilestream.close(); } } // while } void main () { // the input filestream & the number read at each line of the file ifstream infilestream; int number; // the number read from a line int power; // variable to be used to define digit int digit; // the digit of a number. Each number will have 4 digits cout << "Number Splitting from files by Demetris Zeinalipour - Lab 7\n\n"; // function declarations void getFileStream(ifstream& infilestream); // this function does all the work related to opening the file and validation. getFileStream(infilestream); // left-justify any future output (just doi it once!) cout << setiosflags(ios::left); // repeat this loop until you reach the end of that file while (!infilestream.eof()) { // read integer from the file infilestream >> number; // print out this number cout << setw(7) << number; // split and print each digit of this number for (int i=MAX_NUMBER-1; i>=0; i--) { power = (int)pow(10,i); digit = number / power; number %= power; // print ot the cout << setw(7) << digit; } cout << endl; } // !always remember to close the file before quitting infilestream.close(); }