Download presentation
Presentation is loading. Please wait.
Published byErika Bach Modified over 6 years ago
1
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included fro string manipulation? how is a string assigned a value? Can a string be initialized at declaration? how is getline() different from extraction operator? what does this line do? string s1=”hi” + ’ ’ + ”there”; how are strings compared? Which one is greater? hell bell hello how can the size of a string be determined? Can string size be changed? What is the size of this string? string s2=”hello”; is there a problem with this statement? cout << s2[4]; assuming string s3=”C++ is fun”; what do the following functions do? s3.substr(4,2); s3.find(’+’); s3.rfind(’+’); s3.find_first_of(”is”); s3.find_last_of(”is”); s3.insert(3,2,’ ’); s3.replace(1,3,”--”); s3.append(”!!”); s3.erase(0,3);
2
Input/Output
3
Streams C++ uses streams for input and output
stream - is a sequence of data to be read (input stream) or a sequence of data generated by the program to be output (output stream) by default only standard streams are declared: cin (console input) cout (console output) files are used to store information on permanent basis to do file input/output <fstream> needs to be included as well as using std::ifstream; and using std::ofstream; an input or output stream needs to be declared: ifstream fin; // input stream ofstream fout; // output stream before C++ program can read from or write to a file stream, the stream needs to be connected to a file. This is referred to as opening the file: fin.open(”myfile.dat”); // opening file
4
Streams (Cont.) a string variable can be used as file name
c_str() function has to be applied to the string: string filename=”myfile.dat”; fin.open(filename.c_str()); after stream variable has been connected to a file, extraction and insertion operators can be used with a stream: fin >> var1 >> var2 >> var3; after the file is opened all the operations on the file is done through associated stream before program finishes every stream needs to closed: fin.close(); // closing file function eof() returns true if end of input file has been reached: while(!fin.eof()){ … }
5
I/O Error Checking function fail() returns true if previous stream operation failed useful to check if file is opened successfully before performing operations on file useful function exit() - exists program immediately. To use exit, include <cstdlib> exit() accepts one integer as argument: convention: 0 - normal program termination; nonzero - abnormal Example fin.open(”myfile.dat”); // opening file if (fin.fail()){ cout << ”Cannot open file myfile.dat”; exit(1); }
6
Streams as Parameters void myfunc(ifstream &myinfile);
streams can be passed as parameters streams must be passed by reference void myfunc(ifstream &myinfile);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.