Starting Out with C++, 3 rd Edition Basic file operations in C++ Dr. Ahmed Telba
Starting Out with C++, 3 rd Edition 2 Chapter – File Operations
Starting Out with C++, 3 rd Edition What is a File? A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused.
Starting Out with C++, 3 rd Edition File Names All files are assigned a name that is used for identification purposes by the operating system and the user.
Starting Out with C++, 3 rd Edition 5 Table 12-1
Starting Out with C++, 3 rd Edition Focus on Software Engineering: The Process of Using a File Using a file in a program is a simple three- step process –The file must be opened. If the file does not yet exits, opening it means creating it. –Information is then saved to the file, read from the file, or both. –When the program is finished using the file, the file must be closed.
Starting Out with C++, 3 rd Edition 7 Figure 12-1
Starting Out with C++, 3 rd Edition 8 Figure 12-2
Starting Out with C++, 3 rd Edition Setting Up a Program for File Input/Output Before file I/O can be performed, a C++ program must be set up properly. File access requires the inclusion of fstream.h
Starting Out with C++, 3 rd Edition Opening a File Before data can be written to or read from a file, the file must be opened. ifstream inputFile; inputFile.open(“customer.dat”); // Path of file using : ifstream fin("D:\\data.txt ");
Starting Out with C++, 3 rd Edition FLAGES IN FILE
Starting Out with C++, 3 rd Edition 12 // This program demonstrates the declaration of an fstream // object and the opening of a file. #include using namespace std; int main() { char x = 's'; int d = 77; double i = 3.14; ofstream fout("data.txt"); fout << x <<",“ << d<<",“ << ' ' << i ; fout.close(); cout << "File Completed\n";// in screen return 0; }
Starting Out with C++, 3 rd Edition // writing in file #include //divide by 7 #include using namespace std; int main() { ofstream fout("data.txt"); for(int i=4;i<=400;i++) if(i%7==0) //fout << i <<",“ << d<<",“ << ' ' << i ; fout<<i<<" : divide by Two (7)."<<"\n"; fout.close(); //cout<<i<<" : divide by Two (7)."<<"\n"; } 13
Starting Out with C++, 3 rd Edition #include // !x=x*(x-1)*(x-2)…. #include using namespace std; int main() { ofstream fout("factial.txt"); // Variable Declaration int counter, n, fact = 1; // Get Input Value cout<<"Enter the Number :"; cin>>n; //for Loop Block for (int counter = 1; counter <= n; counter++) { fact = fact * counter; } fout<<n<<" Factorial Value Is "<<fact; fout.close(); cout<<n<<" Factorial Value Is "<<fact; return 0; } 14
Starting Out with C++, 3 rd Edition #include >// !x=x*(x-1)*(x-2)…. Using function #include using namespace std; //Function long factorial(int); int main() { ofstream fout("flll.txt"); int counter, n; // Get Input Value cout<<"Enter the Number :"; cin>>n; // Factorial Function Call fout<<n<<" Factorial Value Is "<<factorial(n); cout<<n<<" Factorial Value Is "<<factorial(n); fout.close(); return 0; } // Factorial Function long factorial(int n) { int counter; long fact = 1; //for Loop Block for (int counter = 1; counter <= n; counter++) { fact = fact * counter; } return fact; } 15
Starting Out with C++, 3 rd Edition 16 Program Output with Example Input Enter the name of a file you wish to open or create: mystuff.dat [Enter] The file mystuff.dat was opened.
Starting Out with C++, 3 rd Edition 17 Table 12-3
Starting Out with C++, 3 rd Edition 18 Table 12-4
Starting Out with C++, 3 rd Edition 19 Table 12-4 continued
Starting Out with C++, 3 rd Edition 20 Opening a File at Declaration fstream dataFile(“names.dat”, ios::in | ios::out);
Starting Out with C++, 3 rd Edition 21 Program 12-2 // This program demonstrates the opening of a file at the // time the file stream object is declared. #include using namespace std; main( ) { fstream dataFile("names.txt", ios::in | ios::out); cout << "The file names.dat was opened.\n"; //system("PAUSE"); }
Starting Out with C++, 3 rd Edition 22 Program Output with Example Input The file names.dat was opened.
Starting Out with C++, 3 rd Edition 23 Testing for Open Errors dataFile.open(“cust.txt”, ios::in); if (!dataFile) { cout << “Error opening file.\n”; }
Starting Out with C++, 3 rd Edition 24 Another way to Test for Open Errors dataFile.open(“cust.dat”, ios::in); if (dataFile.fail()) { cout << “Error opening file.\n”; }
Starting Out with C++, 3 rd Edition Closing a File A file should be closed when a program is finished using it.
Starting Out with C++, 3 rd Edition // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a new file created in cpp.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; system("pause"); return 0; }
Starting Out with C++, 3 rd Edition // reading a text file #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; system("pause"); return 0; }
Starting Out with C++, 3 rd Edition file operations in C++ #include using namespace std; int main () { ofstream myfile; myfile.open ("example22.txt"); myfile << "Writing this to a file.\n"; myfile<<"Hope fine”" << endl; myfile<<"this frist file ”" << endl; myfile.close(); system("pause"); return 0; } Slide 6- 28
Starting Out with C++, 3 rd Edition #include using namespace std; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "\nEnter the name of the file you want to create: "; cin >> FileName; ofstream Students(FileName, ios::out); Students << FirstName << "\n" << LastName << "\n" << Age; cout << "\n\n"; return 0; } Slide 6- 29
Starting Out with C++, 3 rd Edition // basic file operations #include using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); system("pause"); return 0; } Slide 6- 30
Starting Out with C++, 3 rd Edition Write to file #include int main() { ofstream fout; fout.open("D:\\firstExa.txt"); fout << "Asalamualikom hope fine.\n" << "WELCOME TO GE 211 FILE SECTION PROGRAM\n" << "HOPE TO DO WELL IN SECOND MEDTERM EXAM\n"; fout.close(); system("pause"); }
Starting Out with C++, 3 rd Edition //Write the odd number in file #include int main() { ofstream fout; fout.open("D:\\firstExa.txt"); int i,j; for(i=2;i<30;i+=2) fout<<i<<"\t"; fout.close(); system("pause"); }
Starting Out with C++, 3 rd Edition // print in file Even number 1:30 #include int main() { ofstream fout; fout.open("D:\\firstExa.txt"); int i,j; for(i=1;i<30;i+=2) fout<<i<<"\t"; fout.close(); system("pause"); }
Starting Out with C++, 3 rd Edition #include main() {ofstream fout; fout.open("D:\\ffffff.txt"); float i,j,m,sum; j=3; sum=0; for(i=1;i<=100;i++){ m=(i*i)/(j*j); j=j+2; sum=sum+m;} cout<<"seque="<<sum<<endl; fout<<"seque="<<sum<<endl; fout.close(); system("pause");}
Starting Out with C++, 3 rd Edition //write equation for this series #include main() { int i,j,m,n,sum; sum=0; cin>>n; for(i=1 ;i<=n ;i++) { m=i*i; sum=sum+m; } cout<< "seque="<<sum<< endl; system("pause"); }
Starting Out with C++, 3 rd Edition #include main() { float i,m,n,b,a,y,x,s; y=0; b=2; cout<<"enter the last power of\n"; cin>>n; cout<<"enter the volue of(x)\n"; cin>>s; for(i=1;i<=n;i++){ x=pow(s,i); a=pow(b,i); m=x/a; y=y+m; } cout<<"y= "<<y; system("pause"); }
Starting Out with C++, 3 rd Edition #include main() {ofstream fout; fout.open("D:\\UUUU.txt"); float i,m,n,b,a,y,x,s; y=0; b=2; cout<<"enter the last power of\n"; cin>>n; cout<<"enter the volue of(x)\n"; cin>>s; for(i=1;i<=n;i++){ x=pow(s,i); a=pow(b,i); m=x/a; y=y+m; } cout<<"y= "<<y; fout<<"y= "<<y; fout.close(); system("pause"); }
Starting Out with C++, 3 rd Edition //Fenonci seris #include main() {ofstream fout; fout.open("D:\\finoncy.txt"); int i,s,b,d ; s=0; d=1; for(i=0;i<20;i++) { b=s; s=d; d=s+b; fout<<d<<"\t"; } fout.close(); system("pause");}
Starting Out with C++, 3 rd Edition //write to file #include main() { ofstream fout; fout.open("D:\\Seris.txt"); int i,j,m,n,sum; sum=0; cin>>n; for(i=1 ;i<=n ;i++) { m=i*i; sum=sum+m; } fout<< "seque="<<sum<< endl; fout.close(); system("pause"); }
Starting Out with C++, 3 rd Edition Read from file #include main() { char array [80]; ifstream fin; fin.open("D:\\firstExa.txt"); while(!fin.eof()) {fin.getline(array,80); cout<<array<<endl;} fin.close(); system("pause"); }
Starting Out with C++, 3 rd Edition FLAGES IN FILE
Starting Out with C++, 3 rd Edition Write in binary file ofstream fout ; fout.open("file path",iostream family fout.write((char*)& data,sizeo(data);
Starting Out with C++, 3 rd Edition Binary form #include main() { int Array[80],i; for(i=0;i<10;i++) cin>> Array[i]; ofstream fout; fout.open("D:\\ahmed.bin",ios::binary); fout.write((char *) & Array, sizeof(Array)); fout.close(); system("pause"); }
Starting Out with C++, 3 rd Edition // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; system("pause"); return 0; } Slide 6- 44
Starting Out with C++, 3 rd Edition // reading a text file #include using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( myfile.good() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; system("pause"); return 0; } Slide 6- 45
Starting Out with C++, 3 rd Edition Slide I/O Streams I/O refers to program input and output –Input is delivered to your program via a stream object –Input can be from The keyboard A file –Output is delivered to the output device via a stream object –Output can be to The screen A file
Starting Out with C++, 3 rd Edition Using fout Slide #include using namespace std; int main (int aaa,char *avg[]) { ofstream fout ("my_out.txt"); fout<<" Assalamualikom Hope fine" << endl; fout<<"Please tray good in second exam this frist file " << endl; system("pause"); return 0;}
Starting Out with C++, 3 rd Edition Write in file #include using namespace std; int main( ) { //cout<<"Exam1\n"; // ifstream ;// read // ofstream ;// write // fstream;//read &write ofstream myfile; myfile.open("kkkk.txt"); myfile<< "Exam1 is ok\n"; myfile<< "please tray good in second exam"; myfile.close(); system("pause"); return 0; }
Starting Out with C++, 3 rd Edition Using fstream #include using namespace std; int main( ) { /*cout<<"Exam1\n"; // ifstream ;// read // ofstream ;// write // fstream;//read &write*/ fstream myfile; myfile.open("kkkk.txt",ios ::out); //myfile<< "Exam1 is ok\n"; myfile<< "please tray good in second exam****************"; //cout<<myfile.rdbuf(); myfile.close(); system("pause"); return 0; }
Starting Out with C++, 3 rd Edition Using app #include using namespace std; int main( ) { /*cout<<"Exam1\n"; ifstream ;// read ofstream ;// write fstream;//read &write*/ fstream myfile; myfile.open("kkkk.txt",ios ::out|ios::app); //myfile<< "Exam1 is ok\n"; myfile<< "please tray good in second exam****************\n"; //cout<<myfile.rdbuf(); myfile.close(); system("pause"); return 0; }
Starting Out with C++, 3 rd Edition Read from file #include using namespace std; int main( ) { /*cout<<"Exam1\n"; ifstream ;// read ofstream ;// write fstream;//read &write*/ ifstream myfile; myfile.open("kkkk.txt"); //myfile<< "Exam1 is ok\n"; //myfile<< "please tray good in second exam"; cout<<myfile.rdbuf(); myfile.close(); system("pause"); return 0; }
Starting Out with C++, 3 rd Edition Input &Output with files Input / Output with files C++ provides the following classes to perform output and input of characters to/from files: ofstream: Stream class to write on files ifstream: Stream class to read from files fstream: Stream class to both read and write from/to files.
Starting Out with C++, 3 rd Edition // basic file operations #include using namespace std; int main () { ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; }
Starting Out with C++, 3 rd Edition classdefault mode parameter ofstreamios::out ifstreamios::in fstreamios::in | ios::out ofstream myfile; myfile.open ("example.bin", ios::out | ios::app | ios::binary);
Starting Out with C++, 3 rd Edition Basic file operations // basic file operations #include //#include using namespace std; int main () { ofstream myfile; myfile.open ("XXX.txt"); myfile << "**Writing this to a file.\n"; myfile << "****Writing this to a file.\n"; myfile << "*********Writing this to a file.\n"; myfile.close(); system("PAUSE"); return 0; }
Starting Out with C++, 3 rd Edition Basic file operations #include using namespace std; int main (int argc, char *arvg[ ]) { ofstream fout("XXX.txt"); fout << "**Writing this to a file.\n"; fout << "****Writing this to a file.\n"; fout << "*********Writing this to a file.\n"; system("PAUSE"); return EXIT_SUCCESS; }
Starting Out with C++, 3 rd Edition FILE IN C++ ios::inOpen for input operations. ios::outOpen for output operations. ios::binaryOpen in binary mode. ios::ate Set the initial position at the end of the file. If this flag is not set to any value, the initial position is the beginning of the file. ios::app All output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations. ios::trunc If the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.
Starting Out with C++, 3 rd Edition // writing on a text file #include using namespace std; int main () { ofstream myfile ("example.txt"); if (myfile.is_open()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close(); } else cout << "Unable to open file"; return 0; }
Starting Out with C++, 3 rd Edition Open a file The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it. In order to open a file with a stream object we use its member function open(): open (filename, mode); Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:
Starting Out with C++, 3 rd Edition
IOS :: IN OPEN FILE FOR READ
Starting Out with C++, 3 rd Edition
65 Program 12-3 // This program demonstrates the close function. #include void main(void) { fstream dataFile; dataFile.open("testfile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File was created successfully.\n"; cout << "Now closing the file.\n"; dataFile.close(); }
Starting Out with C++, 3 rd Edition 66 Program Output File was created successfully. Now closing the file.
Starting Out with C++, 3 rd Edition Using << to Write Information to a File The stream insertion operator (<<) may be used to write information to a file. outputFile << “I love C++ programming !”
Starting Out with C++, 3 rd Edition 68 Program 12-4 // This program uses the << operator to write information to a file. #include void main(void) { fstream dataFile; char line[81]; dataFile.open("demofile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; }
Starting Out with C++, 3 rd Edition 69 Program continues cout << "File opened successfully.\n"; cout << "Now writing information to the file.\n"; dataFile << "Jones\n"; dataFile << "Smith\n"; dataFile << "Willis\n"; dataFile << "Davis\n"; dataFile.close(); cout << "Done.\n"; }
Starting Out with C++, 3 rd Edition 70 Program Screen Output File opened successfully. Now writing information to the file. Done. Output to File demofile.txt Jones Smith Willis Davis
Starting Out with C++, 3 rd Edition 71 Figure 12-3
Starting Out with C++, 3 rd Edition 72 Program 12-5 // This program writes information to a file, closes the file, // then reopens it and appends more information. #include void main(void) { fstream dataFile; dataFile.open("demofile.txt", ios::out); dataFile << "Jones\n"; dataFile << "Smith\n"; dataFile.close(); dataFile.open("demofile.txt", ios::app); dataFile << "Willis\n"; dataFile << "Davis\n"; dataFile.close(); }
Starting Out with C++, 3 rd Edition 73 Output to File demofile.txt Jones Smith Willis Davis
Starting Out with C++, 3 rd Edition File Output Formatting File output may be formatted the same way as screen output.
Starting Out with C++, 3 rd Edition 75 Program 12-6 // This program uses the precision member function of a // file stream object to format file output. #include void main(void) { fstream dataFile; float num = ; dataFile.open("numfile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; }
Starting Out with C++, 3 rd Edition 76 Program continues dataFile << num << endl; dataFile.precision(5); dataFile << num << endl; dataFile.precision(4); dataFile << num << endl; dataFile.precision(3); dataFile << num << endl; }
Starting Out with C++, 3 rd Edition 77 Contents of File numfile.txt
Starting Out with C++, 3 rd Edition 78 Program 12-7 #include void main(void) {fstream outFile("table.txt", ios::out); int nums[3][3] = { 2897, 5, 837, 34, 7, 1623, 390, 3456, 12 }; // Write the three rows of numbers for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { outFile << setw(4) << nums[row][col] << " "; } outFile << endl; } outFile.close(); }
Starting Out with C++, 3 rd Edition 79 Contents of File TABLE.TXT
Starting Out with C++, 3 rd Edition 80 Figure 12-6
Starting Out with C++, 3 rd Edition Using >> to Read Information from a File The stream extraction operator (>>) may be used to read information from a file.
Starting Out with C++, 3 rd Edition 82 Program 12-8 // This program uses the >> operator to read information from a file. #include void main(void) { fstream dataFile; char name[81]; dataFile.open("demofile.txt", ios::in); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.\n"; cout << "Now reading information from the file.\n\n";
Starting Out with C++, 3 rd Edition 83 Program continues for (int count = 0; count < 4; count++) { dataFile >> name; cout << name << endl; } dataFile.close(); cout << "\nDone.\n"; }
Starting Out with C++, 3 rd Edition 84 Program Screen Output File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done.
Starting Out with C++, 3 rd Edition Detecting the End of a File The eof() member function reports when the end of a file has been encountered. if (inFile.eof()) inFile.close();
Starting Out with C++, 3 rd Edition 86 Program 12-9 // This program uses the file stream object's eof() member // function to detect the end of the file. #include void main(void) { fstream dataFile; char name[81]; dataFile.open("demofile.txt", ios::in); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.\n"; cout << "Now reading information from the file.\n\n";
Starting Out with C++, 3 rd Edition 87 Program continues dataFile >> name; // Read first name from the file while (!dataFile.eof()) { cout << name << endl; dataFile >> name; } dataFile.close(); cout << "\nDone.\n"; }
Starting Out with C++, 3 rd Edition 88 Program Screen Output File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done.
Starting Out with C++, 3 rd Edition 89 Note on eof() In C++, “end of file” doesn’t mean the program is at the last piece of information in the file, but beyond it. The eof() function returns true when there is no more information to be read.
Starting Out with C++, 3 rd Edition Passing File Stream Objects to Functions File stream objects may be passed by reference to functions. bool openFileIn(fstream &file, char name[51]) { bool status; file.open(name, ios::in); if (file.fail()) status = false; else status = true; return status; }
Starting Out with C++, 3 rd Edition More Detailed Error Testing All stream objects have error state bits that indicate the condition of the stream.
Starting Out with C++, 3 rd Edition 92 Table 12-5
Starting Out with C++, 3 rd Edition 93 Table 12-6
Starting Out with C++, 3 rd Edition 94 Program // This program demonstrates the return value of the stream // object error testing member functions. #include // Function prototype void showState(fstream &); void main(void) { fstream testFile("stuff.dat", ios::out); if (testFile.fail()) { cout << "cannot open the file.\n"; return; }
Starting Out with C++, 3 rd Edition 95 Program continues int num = 10; cout << "Writing to the file.\n"; testFile << num;// Write the integer to testFile showState(testFile); testFile.close();// Close the file testFile.open("stuff.dat", ios::in);// Open for input if (testFile.fail()) { cout << "cannot open the file.\n"; return; }
Starting Out with C++, 3 rd Edition 96 Program continues cout << "Reading from the file.\n"; testFile >> num;// Read the only number in the file showState(testFile); cout << "Forcing a bad read operation.\n"; testFile >> num;// Force an invalid read operation showState(testFile); testFile.close();// Close the file } // Definition of function ShowState. This function uses // an fstream reference as its parameter. The return values of // the eof(), fail(), bad(), and good() member functions are // displayed. The clear() function is called before the function // returns.
Starting Out with C++, 3 rd Edition 97 Program continues void showState(fstream &file) { cout << "File Status:\n"; cout << " eof bit: " << file.eof() << endl; cout << " fail bit: " << file.fail() << endl; cout << " bad bit: " << file.bad() << endl; cout << " good bit: " << file.good() << endl; file.clear();// Clear any bad bits }
Starting Out with C++, 3 rd Edition 98 Program Output Writing to the file. File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1 Reading from the file. File Status: eof bit: 0 fail bit: 0 bad bit: 0 good bit: 1 Forcing a bad read operation. File Status: eof bit: 1 fail bit: 2 bad bit: 0 good bit: 0
Starting Out with C++, 3 rd Edition Member Functions for Reading and Writing Files File stream objects have member functions for more specialized file reading and writing.
Starting Out with C++, 3 rd Edition 100 Figure 12-8
Starting Out with C++, 3 rd Edition 101 Program // This program uses the file stream object's eof() member // function to detect the end of the file. #include void main(void) { fstream nameFile; char input[81]; nameFile.open("murphy.txt", ios::in); if (!nameFile) { cout << "File open error!" << endl; return; }
Starting Out with C++, 3 rd Edition 102 Program (continued) nameFile >> input; while (!nameFile.eof()) { cout << input; nameFile >> input; } nameFile.close(); }
Starting Out with C++, 3 rd Edition 103 Program Screen Output JayneMurphy47JonesCircleAlmond,NC28702
Starting Out with C++, 3 rd Edition 104 The getline Member Function dataFile.getline(str, 81, ‘\n’); str – This is the name of a character array, or a pointer to a section of memory. The information read from the file will be stored here. 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. ‘\n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading before it has read the maximum number of characters. (This argument is optional. If it’s left our, ‘\n’ is the default.)
Starting Out with C++, 3 rd Edition 105 Program // This program uses the file stream object's getline member // function to read a line of information from the file. #include void main(void) { fstream nameFile; char input[81]; nameFile.open("murphy.txt", ios::in); if (!nameFile) { cout << "File open error!" << endl; return; }
Starting Out with C++, 3 rd Edition 106 Program continues nameFile.getline(input, 81); // use \n as a delimiter while (!nameFile.eof()) { cout << input << endl; nameFile.getline(input, 81); // use \n as a delimiter } nameFile.close(); }
Starting Out with C++, 3 rd Edition 107 Program Screen Output Jayne Murphy 47 Jones Circle Almond, NC 28702
Starting Out with C++, 3 rd Edition 108 Program // This file shows the getline function with a user- // specified delimiter. #include void main(void) { fstream dataFile("names2.txt", ios::in); char input[81]; dataFile.getline(input, 81, '$'); while (!dataFile.eof()) { cout << input << endl; dataFile.getline(input, 81, '$'); } dataFile.close(); }
Starting Out with C++, 3 rd Edition 109 Program Output Jayne Murphy 47 Jones Circle Almond, NC Bobbie Smith 217 Halifax Drive Canton, NC Bill Hammet PO Box 121 Springfield, NC 28357
Starting Out with C++, 3 rd Edition 110 The get Member Function inFile.get(ch);
Starting Out with C++, 3 rd Edition 111 Program // This program asks the user for a file name. The file is // opened and its contents are displayed on the screen. #include void main(void) { fstream file; char ch, fileName[51]; cout << "Enter a file name: "; cin >> fileName; file.open(fileName, ios::in); if (!file) { cout << fileName << “ could not be opened.\n"; return; }
Starting Out with C++, 3 rd Edition 112 Program continues file.get(ch); // Get a character while (!file.eof()) { cout << ch; file.get(ch); // Get another character } file.close(); }
Starting Out with C++, 3 rd Edition 113 The put Member Function outFile.put(ch);
Starting Out with C++, 3 rd Edition 114 Program // This program demonstrates the put member function. #include void main(void) {fstream dataFile("sentence.txt", ios::out); char ch; cout << "Type a sentence and be sure to end it with a "; cout << "period.\n"; while (1) { cin.get(ch); dataFile.put(ch); if (ch == '.') break; } dataFile.close(); }
Starting Out with C++, 3 rd Edition 115 Program Screen Output with Example Input Type a sentence and be sure to end it with a period. I am on my way to becoming a great programmer. [Enter] Resulting Contents of the File SENTENCE.TXT: I am on my way to becoming a great programmer.
Starting Out with C++, 3 rd Edition Focus on Software Engineering: Working with Multiple Files It’s possible to have more than one file open at once in a program.
Starting Out with C++, 3 rd Edition 117 Program // This program demonstrates reading from one file and writing // to a second file. #include #include // Needed for the toupper function void main(void) { ifstream inFile; ofstream outFile("out.txt"); char fileName[81], ch, ch2; cout << "Enter a file name: "; cin >> fileName; inFile.open(fileName); if (!inFile) { cout << "Cannot open " << fileName << endl; return; }
Starting Out with C++, 3 rd Edition 118 Program continues inFile.get(ch); // Get a characer from file 1 while (!inFile.eof()) // Test for end of file { ch2 = toupper(ch); // Convert to uppercase outFile.put(ch2); // Write to file2 inFile.get(ch); // Get another character from file 1 } inFile.close(); outFile.close(); cout << "File conversion done.\n"; }
Starting Out with C++, 3 rd Edition 119 Program Screen Output with Example Input Enter a file name: hownow.txt [Enter] File conversion done. Contents of hownow.txt: how now brown cow. How Now? Resulting Contents of out.txt: HOW NOW BROWN COW. HOW NOW?
Starting Out with C++, 3 rd Edition Binary Files Binary files contain data that is unformatted, and not necessarily stored as ASCII text. file.open(“stuff.dat”, ios::out | ios::binary);
Starting Out with C++, 3 rd Edition 121 Figure 12-9
Starting Out with C++, 3 rd Edition 122 Figure 12-10
Starting Out with C++, 3 rd Edition 123 Program // This program uses the write and read functions. #include void main(void) { fstream file(“NUMS.DAT", ios::out | ios::binary); int buffer[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "Now writing the data to the file.\n"; file.write((char*)buffer, sizeof(buffer)); file.close(); file.open("NUMS.DAT", ios::in); // Reopen the file. cout << "Now reading the data back into memory.\n"; file.read((char*)buffer, sizeof(buffer)); for (int count = 0; count < 10; count++) cout << buffer[count] << " "; file.close(); }
Starting Out with C++, 3 rd Edition 124 Program Screen Output Now writing the data to the file. Now reading the data back into memory
Starting Out with C++, 3 rd Edition Creating Records with Structures Structures may be used to store fixed-length records to a file. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; }; Since structures can contain a mixture of data types, you should always use the ios::binary mode when opening a file to store them.
Starting Out with C++, 3 rd Edition 126 Program // This program demonstrates the use of a structure variable to // store a record of information to a file. #include #include // for toupper // Declare a structure for the record. struct Info { char name[51]; int age; char address1[51]; char address2[51]; char phone[14]; };
Starting Out with C++, 3 rd Edition 127 Program continues void main(void) { fstream people("people.dat", ios::out | ios::binary); Info person; char again; if (!people) { cout << "Error opening file. Program aborting.\n"; return; } do { cout << "Enter the following information about a ” << "person:\n"; cout << "Name: ";
Starting Out with C++, 3 rd Edition 128 Program continues cin.getline(person.name, 51); cout << "Age: "; cin >> person.age; cin.ignore(); // skip over remaining newline. cout << "Address line 1: "; cin.getline(person.address1, 51); cout << "Address line 2: "; cin.getline(person.address2, 51); cout << "Phone: "; cin.getline(person.phone, 14); people.write((char *)&person, sizeof(person)); cout << "Do you want to enter another record? "; cin >> again; cin.ignore(); } while (toupper(again) == 'Y'); people.close(); }
Starting Out with C++, 3 rd Edition 129 Program Screen Output with Example Input Enter the following information about a person: Name: Charlie Baxter [Enter] Age: 42 [Enter] Address line 1: 67 Kennedy Bvd. [Enter] Address line 2: Perth, SC [Enter] Phone: (803) [Enter] Do you want to enter another record? Y [Enter] Enter the following information about a person: Name: Merideth Murney [Enter] Age: 22 [Enter] Address line 1: 487 Lindsay Lane [Enter] Address line 2: Hazelwood, NC [Enter] Phone: (704) [Enter] Do you want to enter another record? N [Enter]
Starting Out with C++, 3 rd Edition Random Access Files Random Access means non-sequentially accessing informaiton in a file. Figure 12-11
Starting Out with C++, 3 rd Edition 131 Table 12-7
Starting Out with C++, 3 rd Edition 132 Table 12-8
Starting Out with C++, 3 rd Edition 133 Program // This program demonstrates the seekg function. #include void main(void) { fstream file("letters.txt", ios::in); char ch; file.seekg(5L, ios::beg); file.get(ch); cout << "Byte 5 from beginning: " << ch << endl; file.seekg(-10L, ios::end); file.get(ch); cout << "Byte 10 from end: " << ch << endl;
Starting Out with C++, 3 rd Edition 134 Program continues file.seekg(3L, ios::cur); file.get(ch); cout << "Byte 3 from current: " << ch << endl; file.close(); }
Starting Out with C++, 3 rd Edition 135 Program Screen Output Byte 5 from beginning: f Byte 10 from end: q Byte 3 from current: u
Starting Out with C++, 3 rd Edition 136 The tellp and tellg Member Functions tellp returns a long integer that is the current byte number of the file’s write position. tellg returns a long integer that is the current byte number of the file’s read position.
Starting Out with C++, 3 rd Edition 137 Program // This program demonstrates the tellg function. #include #include // For toupper void main(void) { fstream file("letters.txt", ios::in); long offset; char ch, again; do { cout << "Currently at position " << file.tellg() << endl; cout << "Enter an offset from the beginning of the file: "; cin >> offset;
Starting Out with C++, 3 rd Edition 138 Program continues file.seekg(offset, ios::beg); file.get(ch); cout << "Character read: " << ch << endl; cout << "Do it again? "; cin >> again; } while (toupper(again) == 'Y'); file.close(); }
Starting Out with C++, 3 rd Edition 139 Program Output with Example Input Currently at position 0 Enter an offset from the beginning of the file: 5 [Enter] Character read: f Do it again? y [Enter] Currently at position 6 Enter an offset from the beginning of the file: 0 [Enter] Character read: a Do it again? y [Enter] Currently at position 1 Enter an offset from the beginning of the file: 20 [Enter] Character read: u Do it again? n [Enter]
Starting Out with C++, 3 rd Edition Opening a File for Both Input and Output You may perform input and output on an fstream file without closing it and reopening it. fstream file(“data.dat”, ios::in | ios::out);
Starting Out with C++, 3 rd Edition 141 Program // This program sets up a file of blank inventory records. #include // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) { fstream inventory("invtry.dat", ios::out | ios::binary); Invtry record = { "", 0, 0.0 };
Starting Out with C++, 3 rd Edition 142 Program continues // Now write the blank records for (int count = 0; count < 5; count++) { cout << "Now writing record " << count << endl; inventory.write((char *)&record, sizeof(record)); } inventory.close(); }
Starting Out with C++, 3 rd Edition 143 Program Screen Output Now writing record 0 Now writing record 1 Now writing record 2 Now writing record 3 Now writing record 4
Starting Out with C++, 3 rd Edition 144 Program // This program displays the contents of the inventory file. #include // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) { fstream inventory("invtry.dat", ios::in | ios::binary); Invtry record = { "", 0, 0.0 };
Starting Out with C++, 3 rd Edition 145 Program continues // Now read and display the records inventory.read((char *)&record, sizeof(record)); while (!inventory.eof()) { cout << "Description: "; cout << record.desc << endl; cout << "Quantity: "; cout << record.qty << endl; cout << "Price: "; cout << record.price << endl << endl; inventory.read((char *)&record, sizeof(record)); } inventory.close(); }
Starting Out with C++, 3 rd Edition 146 Here is the screen output of Program if it is run immediately after Program sets up the file of blank records. Program Screen Output Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0 Description: Quantity: 0 Price: 0.0
Starting Out with C++, 3 rd Edition 147 Program // This program allows the user to edit a specific record in // the inventory file. #include // Declaration of Invtry structure struct Invtry { char desc[31]; int qty; float price; }; void main(void) {
Starting Out with C++, 3 rd Edition 148 Program continues fstream inventory("invtry.dat", ios::in | ios::out | ios::binary); Invtry record; long recNum; cout << "Which record do you want to edit?"; cin >> recNum; inventory.seekg(recNum * sizeof(record), ios::beg); inventory.read((char *)&record, sizeof(record)); cout << "Description: "; cout << record.desc << endl; cout << "Quantity: "; cout << record.qty << endl; cout << "Price: "; cout << record.price << endl; cout << "Enter the new data:\n"; cout << "Description: ";
Starting Out with C++, 3 rd Edition 149 Program continues cin.ignore(); cin.getline(record.desc, 31); cout << "Quantity: "; cin >> record.qty; cout << "Price: "; cin >> record.price; inventory.seekp(recNum * sizeof(record), ios::beg); inventory.write((char *)&record, sizeof(record)); inventory.close(); }
Starting Out with C++, 3 rd Edition 150 Program Screen Output with Example Input Which record do you ant to edit? 2 [Enter] Description: Quantity: 0 Price: 0.0 Enter the new data: Description: Wrench [Enter] Quantity: 10 [Enter] Price: 4.67 [Enter]
Starting Out with C++, 3 rd Edition
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes
Starting Out with C++, 3 rd Edition Slide Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O
Starting Out with C++, 3 rd Edition Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 6.1 Streams and Basic File I/O
Starting Out with C++, 3 rd Edition Slide I/O Streams I/O refers to program input and output –Input is delivered to your program via a stream object –Input can be from The keyboard A file –Output is delivered to the output device via a stream object –Output can be to The screen A file
Starting Out with C++, 3 rd Edition Slide Objects Objects are special variables that –Have their own special-purpose functions –Set C++ apart from earlier programming languages
Starting Out with C++, 3 rd Edition Slide Streams and Basic File I/O Files for I/O are the same type of files used to store programs A stream is a flow of data. –Input stream: Data flows into the program If input stream flows from keyboard, the program will accept data from the keyboard If input stream flows from a file, the program will accept data from the file –Output stream: Data flows out of the program To the screen To a file
Starting Out with C++, 3 rd Edition Slide cin And cout Streams cin –Input stream connected to the keyboard cout –Output stream connected to the screen cin and cout defined in the iostream library –Use include directive: #include You can declare your own streams to use with files.
Starting Out with C++, 3 rd Edition Slide Why Use Files? Files allow you to store data permanently! Data output to a file lasts after the program ends An input file can be used over and over –No typing of data again and again for testing Create a data file or read an output file at your convenience Files allow you to deal with larger data sets
Starting Out with C++, 3 rd Edition Slide File I/O Reading from a file –Taking input from a file –Done from beginning to the end (for now) No backing up to read something again (OK to start over) Just as done from the keyboard Writing to a file –Sending output to a file –Done from beginning to end (for now) No backing up to write something again( OK to start over) Just as done to the screen
Starting Out with C++, 3 rd Edition Slide Stream Variables Like other variables, a stream variable… –Must be declared before it can be used –Must be initialized before it contains valid data Initializing a stream means connecting it to a file The value of the stream variable can be thought of as the file it is connected to –Can have its value changed Changing a stream value means disconnecting from one file and connecting to another
Starting Out with C++, 3 rd Edition Slide Streams and Assignment A stream is a special kind of variable called an object –Objects can use special functions to complete tasks Streams use special functions instead of the assignment operator to change values
Starting Out with C++, 3 rd Edition Slide Declaring An Input-file Stream Variable Input-file streams are of type ifstream Type ifstream is defined in the fstream library –You must use the include and using directives #include using namespace std; Declare an input-file stream variable using ifstream in_stream;
Starting Out with C++, 3 rd Edition Slide Declaring An Output-file Stream Variable Ouput-file streams of are type ofstream Type ofstream is defined in the fstream library –You must use these include and using directives #include using namespace std; Declare an input-file stream variable using ofstream out_stream;
Starting Out with C++, 3 rd Edition Slide Once a stream variable is declared, connect it to a file –Connecting a stream to a file is opening the file –Use the open function of the stream object in_stream.open("infile.dat"); Period File name on the disk Double quotes Connecting To A File
Starting Out with C++, 3 rd Edition Slide Using The Input Stream Once connected to a file, the input-stream variable can be used to produce input just as you would use cin with the extraction operator –Example: int one_number, another_number; in_stream >> one_number >> another_number;
Starting Out with C++, 3 rd Edition Slide Using The Output Stream An output-stream works similarly to the input-stream –ofstream out_stream; out_stream.open("outfile.dat"); out_stream << "one number = " << one_number << "another number = " << another_number;
Starting Out with C++, 3 rd Edition Slide External File Names An External File Name… –Is the name for a file that the operating system uses infile.dat and outfile.dat used in the previous examples –Is the "real", on-the-disk, name for a file –Needs to match the naming conventions on your system –Usually only used in the stream's open statement –Once open, referred to using the name of the stream connected to it.
Starting Out with C++, 3 rd Edition After using a file, it should be closed –This disconnects the stream from the file –Close files to reduce the chance of a file being corrupted if the program terminates abnormally It is important to close an output file if your program later needs to read input from the output file The system will automatically close files if you forget as long as your program ends normally Slide Display 6.1 Closing a File
Starting Out with C++, 3 rd Edition Slide Objects An object is a variable that has functions and data associated with it –in_stream and out_stream each have a function named open associated with them –in_stream and out_stream use different versions of a function named open One version of open is for input files A different version of open is for output files
Starting Out with C++, 3 rd Edition Slide Member Functions A member function is a function associated with an object –The open function is a member function of in_stream in the previous examples –A different open function is a member function of out_stream in the previous examples
Starting Out with C++, 3 rd Edition Slide Objects and Member Function Names Objects of different types have different member functions –Some of these member functions might have the same name Different objects of the same type have the same member functions
Starting Out with C++, 3 rd Edition Slide Classes A type whose variables are objects, is a class –ifstream is the type of the in_stream variable (object) –ifstream is a class –The class of an object determines its member functions –Example: ifstream in_stream1, in_stream2; in_stream1.open and in_stream2.open are the same function but might have different arguments
Starting Out with C++, 3 rd Edition Slide Class Member Functions Member functions of an object are the member functions of its class The class determines the member functions of the object –The class ifstream has an open function –Every variable (object) declared of type ifstream has that open function
Starting Out with C++, 3 rd Edition Slide Calling object Dot operator Member function Calling a Member Function Calling a member function requires specifying the object containing the function The calling object is separated from the member function by the dot operator Example: in_stream.open("infile.dat");
Starting Out with C++, 3 rd Edition Slide Member Function Calling Syntax Syntax for calling a member function: Calling_object.Member_Function_Name(Argument_list);
Starting Out with C++, 3 rd Edition Slide Errors On Opening Files Opening a file could fail for several reasons –Common reasons for open to fail include The file might not exist The name might be typed incorrectly May be no error message if the call to open fails –Program execution continues!
Starting Out with C++, 3 rd Edition Slide Catching Stream Errors Member function fail, can be used to test the success of a stream operation –fail returns a boolean type (true or false) –fail returns true if the stream operation failed
Starting Out with C++, 3 rd Edition Slide Halting Execution When a stream open function fails, it is generally best to stop the program The function exit, halts a program –exit returns its argument to the operating system –exit causes program execution to stop –exit is NOT a member function Exit requires the include and using directives #include using namespace std;
Starting Out with C++, 3 rd Edition Immediately following the call to open, check that the operation was successful: in_stream.open("stuff.dat"); if( in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1) ; } Slide Display 6.2 Using fail and exit
Starting Out with C++, 3 rd Edition Slide Techniques for File I/O When reading input from a file… –Do not include prompts or echo the input The lines cout > the_number; cout > the_number; –The input file must contain exactly the data expected
Starting Out with C++, 3 rd Edition Output examples so far create new files –If the output file already contains data, that data is lost To append new output to the end an existing file –use the constant ios::app defined in the iostream library: outStream.open("important.txt", ios::app); –If the file does not exist, a new file will be created Slide Display 6.3 Appending Data (optional)
Starting Out with C++, 3 rd Edition Slide File Names as Input (optional) Program users can enter the name of a file to use for input or for output Program must use a variable that can hold multiple characters –A sequence of characters is called a string –Declaring a variable to hold a string of characters: char file_name[16]; file_name is the name of a variable Brackets enclose the maximum number of characters + 1 The variable file_name contains up to 15 characters
Starting Out with C++, 3 rd Edition char file_name[16]; cout > file_name; ifstream in_stream; in_stream.open(file_name); if (in_stream.fail( ) ) { cout << "Input file opening failed.\n"; exit(1); } Slide Display 6.4 (1) Display 6.4 (2) Using A Character String
Starting Out with C++, 3 rd Edition Slide Section 6.1 Conclusion Can you –Write a program that uses a stream called fin which will be connected to an input file and a stream called fout which will be connected to an output file? How do you declare fin and fout? What include directive, if any, do you nee to place in your program file? –Name at least three member functions of an iostream object and give examples of usage of each?
Starting Out with C++, 3 rd Edition Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 6.2 Tools for Streams I/O
Starting Out with C++, 3 rd Edition Slide Tools for Stream I/O To control the format of the program's output –We use commands that determine such details as: The spaces between items The number of digits after a decimal point The numeric style: scientific notation for fixed point Showing digits after a decimal point even if they are zeroes Showing plus signs in front of positive numbers Left or right justifying numbers in a given space
Starting Out with C++, 3 rd Edition Slide Formatting Output to Files Format output to the screen with: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); Format output to a file using the out-file stream named out_stream with: out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2);
Starting Out with C++, 3 rd Edition Slide out_stream.precision(2); precision is a member function of output streams –After out_stream.precision(2); Output of numbers with decimal points… will show a total of 2 significant digits e e OR will show 2 digits after the decimal point e e-4 Calls to precision apply only to the stream named in the call
Starting Out with C++, 3 rd Edition Slide setf(ios::fixed); setf is a member function of output streams –setf is an abbreviation for set flags A flag is an instruction to do one of two options ios::fixed is a flag –After out_stream.setf(ios::fixed); All further output of floating point numbers… Will be written in fixed-point notation, the way we normally expect to see numbers Calls to setf apply only to the stream named in the call
Starting Out with C++, 3 rd Edition After out_stream.setf(ios::showpoint); Output of floating point numbers… Will show the decimal point even if all digits after the decimal point are zeroes Slide Display 6.5 setf(ios::showpoint);
Starting Out with C++, 3 rd Edition Slide (ios::right) (ios::left) Creating Space in Output The width function specifies the number of spaces for the next item –Applies only to the next item of output Example: To print the digit 7 in four spaces use out_stream.width(4); out_stream << 7 << endl; –Three of the spaces will be blank
Starting Out with C++, 3 rd Edition Slide Not Enough Width? What if the argument for width is too small? –Such as specifying cout.width(3); when the value to print is The entire item is always output –If too few spaces are specified, as many more spaces as needed are used
Starting Out with C++, 3 rd Edition Slide Unsetting Flags Any flag that is set, may be unset Use the unsetf function –Example: cout.unsetf(ios::showpos); causes the program to stop printing plus signs on positive numbers
Starting Out with C++, 3 rd Edition Slide Manipulators A manipulator is a function called in a nontraditional way –Manipulators in turn call member functions –Manipulators may or may not have arguments –Used after the insertion operator (<<) as if the manipulator function call is an output item
Starting Out with C++, 3 rd Edition Slide Two SpacesFour Spaces The setw Manipulator setw does the same task as the member function width –setw calls the width function to set spaces for output Example: cout << "Start" << setw(4) << 10 << setw(4) << setw(6) << 30; produces: Start
Starting Out with C++, 3 rd Edition Slide The setprecision Manipulator setprecision does the same task as the member function precision Example: cout.setf(ios::fixed); cout.setf(ios::showpoint); cout << "$" << setprecision(2) << 10.3 << endl << "$" << 20.5 << endl; produces: $10.30 $20.50 –setprecision setting stays in effect until changed
Starting Out with C++, 3 rd Edition Slide Manipulator Definitions The manipulators setw and setprecision are defined in the iomanip library –To use these manipulators, add these lines #include using namespace std;
Starting Out with C++, 3 rd Edition Slide Stream Names as Arguments Streams can be arguments to a function –The function's formal parameter for the stream must be call-by-reference Example: void make_neat(ifstream& messy_file, ofstream& neat_file);
Starting Out with C++, 3 rd Edition Slide The End of The File Input files used by a program may vary in length –Programs may not be able to assume the number of items in the file A way to know the end of the file is reached: –The boolean expression (in_stream >> next) Reads a value from in_stream and stores it in next True if a value can be read and stored in next False if there is not a value to be read (the end of the file)
Starting Out with C++, 3 rd Edition Slide End of File Example To calculate the average of the numbers in a file – double next, sum = 0; int count = 0; while(in_stream >> next) { sum = sum + next; count++; } double average = sum / count;
Starting Out with C++, 3 rd Edition Slide Stream Arguments and Namespaces Using directives have been local to function definitions in the examples so far When parameter type names are in a namespace –A using directive must be outside the function so C++ will understand the parameter type names such as ifstream Easy solution is to place the using directive at the beginning of the file –Many experts do not approve as this does not allow using multiple namespaces with names in common
Starting Out with C++, 3 rd Edition The program in Display 6.6… –Takes input from rawdata.dat –Writes output to the screen and to neat.dat Formatting instructions are used to create a neater layout Numbers are written one per line in a field width of 12 Each number is written with 5 digits after the decimal point Each number is written with a plus or minus sign –Uses function make_neat that has formal parameters for the input-file stream and output-file stream Slide Display 6.6 (1)Display 6.6 (2)Display 6.6 (3) Program Example
Starting Out with C++, 3 rd Edition Slide Section 6.2 Conclusion Can you –Show the output produced when the following line is executed? cout << "*" << setw(3) << << "*" endl; –Describe the effect of each of these flags? Ios::fixed ios::scientificios::showpoint ios::rightios::rightios::showpos
Starting Out with C++, 3 rd Edition Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 6.3 Character I/O
Starting Out with C++, 3 rd Edition Slide Character I/O All data is input and output as characters –Output of the number 10 is two characters '1' and '0' –Input of the number 10 is also done as '1' and '0' –Interpretation of 10 as the number 10 or as characters depends on the program –Conversion between characters and numbers is usually automatic
Starting Out with C++, 3 rd Edition Slide Low Level Character I/O Low level C++ functions for character I/O –Perform character input and output –Do not perform automatic conversions –Allow you to do input and output in anyway you can devise
Starting Out with C++, 3 rd Edition Slide Member Function get Function get –Member function of every input stream –Reads one character from an input stream –Stores the character read in a variable of type char, the single argument the function takes –Does not use the extraction operator (>>) which performs some automatic work –Does not skip blanks
Starting Out with C++, 3 rd Edition Slide Using get These lines use get to read a character and store it in the variable next_symbol char next_symbol; cin.get(next_symbol); –Any character will be read with these statements Blank spaces too! '\n' too! (The newline character)
Starting Out with C++, 3 rd Edition Slide get Syntax input_stream.get(char_variable); Examples: char next_symbol; cin.get(next_symbol); ifstream in_stream; in_stream.open("infile.dat"); in_stream.get(next_symbol);
Starting Out with C++, 3 rd Edition Slide More About get Given this code:char c1, c2, c3; cin.get(c1); cin.get(c2); cin.get(c3); and this input: AB CD c1 = 'A' c2 = 'B' c3 = '\n' –cin >> c1 >> c2 >> c3; would place 'C' in c3 (the ">>" operator skips the newline character)
Starting Out with C++, 3 rd Edition Slide The End of The Line To read and echo a line of input – Look for '\n' at the end of the input line: cout<<"Enter a line of input and I will " << "echo it.\n"; char symbol; do { cin.get(symbol); cout << symbol; } while (symbol != '\n'); –All characters, including '\n' will be output
Starting Out with C++, 3 rd Edition Slide '\n ' vs "\n " '\n' –A value of type char –Can be stored in a variable of type char "\n" –A string containing only one character –Cannot be stored in a variable of type char In a cout-statement they produce the same result
Starting Out with C++, 3 rd Edition Slide Member Function put Function put –Member function of every output stream –Requires one argument of type char –Places its argument of type char in the output stream –Does not do allow you to do more than previous output with the insertion operator and cout
Starting Out with C++, 3 rd Edition Slide put Syntax Output_stream.put(Char_expression); Examples: cout.put(next_symbol); cout.put('a'); ofstream out_stream; out_stream.open("outfile.dat"); out_stream.put('Z');
Starting Out with C++, 3 rd Edition Slide Member Function putback The putback member function places a character in the input stream –putback is a member function of every input stream –Useful when input continues until a specific character is read, but you do not want to process the character –Places its argument of type char in the input stream –Character placed in the stream does not have to be a character read from the stream
Starting Out with C++, 3 rd Edition Slide putback Example The following code reads up to the first blank in the input stream fin, and writes the characters to the file connected to the output stream fout –fin.get(next); while (next != ' ') { fout.put(next); fin.get(next); } fin.putback(next); –The blank space read to end the loop is put back into the input stream
Starting Out with C++, 3 rd Edition Slide Program Example Checking Input Incorrect input can produce worthless output Use input functions that allow the user to re-enter input until it is correct, such as –Echoing the input and asking the user if it is correct –If the input is not correct, allow the user to enter the data again
Starting Out with C++, 3 rd Edition Slide Checking Input:get_int The get_int function seen in Display 6.7 obtains an integer value from the user –get_int prompts the user, reads the input, and displays the input –After displaying the input, get_int asks the user to confirm the number and reads the user's response using a variable of type character –The process is repeated until the user indicates with a 'Y' or 'y' that the number entered is correct
Starting Out with C++, 3 rd Edition The new_line function seen in Display 6.7 is called by the get_int function –new_line reads all the characters remaining in the input line but does nothing with them, essentially discarding them –new_line is used to discard what follows the first character of the the user's response to get_line's "Is that correct? (yes/no)" The newline character is discarded as well Slide Display 6.7 (1) Display 6.7 (2) Checking Input:new_line
Starting Out with C++, 3 rd Edition Slide Checking Input: Check for Yes or No? get_int continues to ask for a number until the user responds 'Y' or 'y' using the do-while loop do { // the loop body } while ((ans !='Y') &&(ans != 'y') ) Why not use ((ans =='N') | | (ans == 'n') )? –User must enter a correct response to continue a loop tested with ((ans =='N') | | (ans == 'n') ) What if they mis-typed "Bo" instead of "No"? –User must enter a correct response to end the loop tested with ((ans !='Y') &&(ans != 'y') )
Starting Out with C++, 3 rd Edition Slide Mixing cin >> and cin.get Be sure to deal with the '\n' that ends each input line if using cin >> and cin.get –"cin >>" reads up to the '\n' –The '\n' remains in the input stream –Using cin.get next will read the '\n' –The new_line function from Display 6.7 can be used to clear the '\n'
Starting Out with C++, 3 rd Edition Slide The Dialogue: Enter a number: 21 Now enter a letter: A The Result: number = 21 symbol = '\n' '\n' Example The Code: cout > number; cout << "Now enter a letter:\n"; char symbol; cin.get(symbol);
Starting Out with C++, 3 rd Edition Slide A Fix To Remove '\n' cout > number; cout >symbol;
Starting Out with C++, 3 rd Edition Slide Another '\n' Fix cout > number; new_line( ); // From Display 6.7 cout << "Now enter a letter:\n"; char symbol; cin.get(symbol);
Starting Out with C++, 3 rd Edition Slide Detecting the End of a File Member function eof detects the end of a file –Member function of every input-file stream –eof stands for end of file –eof returns a boolean value True when the end of the file has been reached False when there is more data to read –Normally used to determine when we are NOT at the end of the file Example: if ( ! in_stream.eof( ) )
Starting Out with C++, 3 rd Edition Slide Using eof This loop reads each character, and writes it to the screen in_stream.get(next); while (! in_stream.eof( ) ) { cout << next; in_stream.get(next); } ( ! In_stream.eof( ) ) becomes false when the program reads past the last character in the file
Starting Out with C++, 3 rd Edition Slide The End Of File Character End of a file is indicated by a special character in_stream.eof( ) is still true after the last character of data is read in_stream.eof( ) becomes false when the special end of file character is read
Starting Out with C++, 3 rd Edition Slide How To Test End of File We have seen two methods –while ( in_stream >> next) –while ( ! in_stream.eof( ) ) Which should be used? –In general, use eof when input is treated as text and using a member function get to read input –In general, use the extraction operator method when processing numeric data
Starting Out with C++, 3 rd Edition The program of Display 6.8… –Reads every character of file cad.dat and copies it to file cplusad.dat except that every 'C' is changed to "C++" in cplusad.dat –Preserves line breaks in cad.dat get is used for input as the extraction operator would skip line breaks get is used to preserve spaces as well – Uses eof to test for end of file Slide Display 6.8 (1) Display 6.8 (2) Program Example: Editing a Text File
Starting Out with C++, 3 rd Edition Slide Character Functions Several predefined functions exist to facilitate working with characters The cctype library is required –#include using namespace std;
Starting Out with C++, 3 rd Edition Slide The toupper Function toupper returns the argument's upper case character –toupper('a') returns 'A' –toupper('A') return 'A'
Starting Out with C++, 3 rd Edition Slide toupper Returns An int Characters are actually stored as an integer assigned to the character toupper and tolower actually return the integer representing the character –cout << toupper('a'); //prints the integer for 'A' –char c = toupper('a'); //places the integer for 'A' in c cout << c; //prints 'A' –cout (toupper('a')); //works too
Starting Out with C++, 3 rd Edition isspace returns true if the argument is whitespace –Whitespace is spaces, tabs, and newlines –isspace(' ') returns true –Example: if (isspace(next) ) cout << '-'; else cout << next; –Prints a '-' if next contains a space, tab, or newline character See more character functions in Slide Display 6.9 (1) Display 6.9 (2) The isspace Function
Starting Out with C++, 3 rd Edition Slide Section 6.3 Conclusion Can you –Write code that will read a line of text and echo the line with all the uppercase letters deleted? –Describe two methods to detect the end of an input file: –Describe whitespace?
Starting Out with C++, 3 rd Edition Slide Chapter 6 -- End
Starting Out with C++, 3 rd Edition Display 6.1 Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.2 Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.3 Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.4 (1/2) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.4 (2/2) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.5 Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.6 (1/3) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.6 (2/3) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.6 (3/3) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.7 (1/2) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.7 (2/2) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.8 (1/2) Slide Next Back
Starting Out with C++, 3 rd Edition Display 6.8 (2/2) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.9 (1/2) Slide Back Next
Starting Out with C++, 3 rd Edition Display 6.9 (2/2) Slide Back Next