C++ Read Single Character From File Skipws


Office F - Refinements

Input and Output Refinements

Utilize stream objects to collaborate with users and access persistent data
Innovate manipulators to format data for input and output objects
Describe the member functions that manage the state of streaming objects

"Designing and implementing a general input/output facility for a programming language is notoriously difficult. ... Nobody has come up up with a solution that pleases anybody" (Stroustrup, 1997)

Stream Classes | Input | Output | Manipulators
State | Robust Validation | File Stream Classes | Summary | Exercises

The chapter entitled Member Functions and Privacy covered the public member functions that format data passing through the standard library's iostream objects.  The affiliate entitled Input and Output Operators covered the design of custom input and output operators and introduced the standard library'southward fstream classes for processing file data.

This chapter describes in more detail the input and output objects along with their public fellow member functions reviews the material covered in those preceding chapters.  This chapter introduces manipulators as a simplifying alternative to fellow member role calls on input and output objects.

Stream and Stream Objects

A stream is a sequence of items without limitation.  More specifically, in C++ a stream is a sequence of bytes.  An executing application accepts data in one stream and outputs data in another stream.  The number of bytes in a stream tin can be indeterminate.  Input objects store data from an input stream in the application's memory.  Output objects re-create data from the application'due south memory into an output stream.  Both input and output objects operate in FIFO (Starting time In First Out) gild.

file streams

The standard input and output objects of the iostream library represent the standard peripheral devices, such as the keyboard and display.

An input object converts a sequence of bytes from its attached input stream into values of specified type, which are stored in organisation retentivity.  An output object converts values of specified type, which have been stored in organisation memory, into a sequence of bytes in its associated output stream.  Both types of objects use the data type associated with the region of memory to make the appropriate conversions from or to the sequence of bytes in each stream.

memory i o

The data in a stream, different the data stored in a region of retention, is non associated with whatsoever particular type.  The notion of type is programming linguistic communication specific.

Input Objects

An input object is an instance of the istream grade.  The istream form defines the structure of an input device.  The object extracts data from the input stream and stores it in arrangement memory, converting each sequence of bytes in the input stream into an equivalent value in organisation retentiveness based on the specified variable'due south type.

Extraction

The expression for extracting bytes from an input stream takes the class

                  inputObject                  >>                  identifier                

where inputObject is the name of the input object, >> is the extraction operator and identifier is the proper noun of the destination variable.

The standard iostream library defines one input object for buffered input: cin.

For instance,

                          int i;  char c;  double x;  char s[8];  cout << "Enter an integer,\n"          "a character,\northward"          "a floating-bespeak number and\n"          "a string : " << flush;                          cin >> i;  cin >> c;  cin >> 10;  cin >> s;  // possible overflow                          cout << "Entered " << i << ' '       << c << ' ' << 10 << ' ' << s << endl;                        
                            Enter an integer,  a graphic symbol,  a floating-point and  a string : half dozen  -  ix.75  Harry      Entered vi - 9.75 Harry                        

Each expression that takes an istream object as its left operand converts the next sequence of bytes in the attached input stream into a value stored in the type of the expression'due south right operand.

The cin object skips leading whitespace with numeric, string and character types (in the same manner that scanf("%d"...), scanf("%lf"...), scanf("%s"...) and scanf(" %c"...) skip whitespace in C).

                          // Leading Whitespace  // leading.cpp   #include <iostream>  using namespace std;   int principal() {      char str[eleven];       cout << "Enter a string : " << endl;      cin >> str;      cout << "|" << str << "|" << endl;   }                        
                            Note: _ denotes infinite       Enter a string :  __abc  |abc|                        

Whitespace

The input object treats whitespace in its input stream every bit a delimiter for numeric and string data types.  In converting input bytes into a C-style nada-terminated string, the input object adds the null byte subsequently the last non-whitespace character stored in memory:

                          // Abaft Whitespace  // trailing.cpp   #include <iostream>  using namespace std;   int master() {      char str[11];       cout << "Enter a string : " << endl;      cin >> str;      cout << "|" << str << "|" << endl;   }                        
                            Note: _ denotes space       Enter a cord :  __abc__  |abc|                        

Cascading

We tin can compress a sequence of extraction operations into a single chemical compound expression:

                          int i;  char c;  double x;  char s[viii];  cout << "Enter an integer,\n"          "a grapheme,\north"          "a floating-point number and\n"          "a string : " << flush;                          cin >> i >> c >> x >> s;                          cout << "Entered " << i << ' '       << c << ' ' << ten << ' ' << s << endl;                        
                            Enter an integer,  a character,  a floating-indicate and  a string : vi  -  9.75  Harry   Entered six - nine.75 Harry                        

We call such repeated use of the extraction operator cascading.

Note that reading a sequence of bytes in this manner is discouraged (encounter beneath).

Overflow

In the in a higher place 2 examples, overflow may occur while filling s.  The extraction operator >> does not restrict the number of bytes accepted.  If more than vii bytes are in the input stream the data stored for the string may corrupt other data that has been stored in memory equally shown on the correct:

                          // Overflow  // overflow.cpp   #include <iostream>  using namespace std;   int main() {      int i;      char c;      double x;      char southward[8];      cout << "Enter an integer,\northward"          "a character,\northward"          "a floating-point number and\n"          "a string : \northward";                          cin >> i >> c >> x >> s;                          cout << "Entered " << endl;      cout << i << ' '           << c << ' ' << x << ' ' << s << endl;   }                        
                            Enter an integer,  a grapheme,  a floating-signal and  a cord :  half dozen - nine.75 Constantinople   Entered  6 -                          2.04952                          Constantinople                        

The corruption varies from platform to platform.

Member Functions

The istream type supports the following fellow member functions:

  • ignore(...) - ignores/discards character(s) from the input buffer
  • get(...) - extracts a character or a cord from the input buffer
  • getline(...) - extracts a line of characters from the input buffer

ignore

The ignore() member function extracts bytes from the input buffer and discards them without skipping whitespace.  The iostream bureaucracy defines 2 overloaded versions of ignore():

                    cin.ignore();  cin.ignore(2000, '\n');                                      

The no-argument version discards a unmarried byte.  The ii-argument version removes and discards upwardly to the number of bytes specified by the start argument or upwards to the specified delimiting grapheme, whichever occurs first and discards the delimiting character.  The default delimiter is the end-of-file character (not the newline character).

get

The get() member office extracts either a single character or a string from the input buffer.  Three versions are available:

                    // Input Extraction Using get()  // get.cpp   #include <iostream>  using namespace std;   int master() {      char c, d, t[8], u[viii], v;                    c = cin.get();                    // extracts a single character                    cin.get(d);                    // extracts a single character                    cin.go(t, viii);                    // newline delimiter - accepts upwards to 7 chars                               //    and adds a null byte      cin.ignore(2000, '\due north'); // extracts the 'j' and the newline                    cin.get(u, 8, '\t');                    // tab delimiter - accepts up to 7 chars and                              //    adds a zilch byte      cin.ignore();           // extracts the tab                    cin.get(v);                    // extracts a single grapheme       cout << "c = " << c << endl;      cout << "d = " << d << endl;      cout << "t = " << t << endl;      cout << "u = " << u << endl;      cout << "v = " << v << endl;  }                  

The above plan produces the following results for the input shown (the grapheme _ refers to the horizontal tab character):

                    Input stream : abcdefghij                 klmn_opqr  Output:  -------  c = a  d = b  t = cdefghi  u = klmn  v = o                  

get() does non skip leading whitespace. get(,) leaves the delimiting grapheme in the input buffer.  In using get(,) we demand to remove the delimiting graphic symbol, if there is one.  Both string versions - get(char*, int) and get(char*, int, char) - append a null byte to the sequence of characters stored in memory.

getline

getline() behaves like become(), simply extracts the delimiting character from the input buffer:

                    // Input Extraction using getline()  // getline.cpp   #include <iostream>  using namespace std;   int principal() {      char t[8], u[8], v;                    cin.getline(t, viii);                    // newline delimiter - accepts upwardly to 7 chars                                //    and adds a null byte                    cin.getline(u, eight, '\t');                    // tab delimiter - accepts up to 7 chars and                               //    adds a cipher byte      cin.become(five);              // extracts a single graphic symbol       cout << "t = " << t << endl;      cout << "u = " << u << endl;      cout << "v = " << v << endl;  }                  

The above program produces the post-obit results for the input shown (the character _ refers to the horizontal tab graphic symbol):

                    Note: _ denotes '\t' grapheme hither   Input stream : cdefghi                 jklmn_opqr  Output:  -------  t = cdefghi  u = jklmn  v = o                  

getline(), similar go(), does not skip leading whitespace and appends a aught byte to the sequence of characters stored in organisation memory.

Output Objects

An output object is an case of the ostream grade.  The ostream class defines the structure of an output device.  An ostream object copies data from system memory into an output stream; in copying, it converts the data in arrangement memory into a sequence of characters.

The standard iostream library defines three distinct standard output objects:

  • cout - transfers a buffered sequence of characters to the standard output device
  • cerr - transfers an unbuffered sequence of characters to the standard fault output device
  • clog - transfers a buffered sequence of characters to the standard error output device

Inserting Data

The expression for inserting data into an output stream takes the form

                  output                  <<                  identifier                

where output is the name of the ostream object, << is the insertion operator and identifier is the name of the variable or object that holds the data.

For example,

                          int i = vi;  char c = ' ';  double x = 9.75;  char s[] = "Harry";  cout                          <<                          i;  cout                          <<                          c;  cout                          <<                          ten;  cout                          <<                          c;  cout                          <<                          south;  cout                          <<                          endl;  cerr                          <<                          "Information has been written";                        
                            6 9.75 Harry                        

                          Data has been written                        

Each expression that takes an ostream object every bit its left operand converts the data in its right operand into a sequence of characters based on the type of the expression's right operand.

endl inserts a newline character into the output stream and flushes the stream'due south buffer.

Cascading

Nosotros may combine a sequence of insertion operations into a compound insertion expression:

                          int i = 6;  char c = ' ';  double x = 9.75;  char s[] = "Harry";                          cout << i << c << x << c << southward << endl;    cerr << "Data has been written";                        
                            vi 9.75 Harry                        
                          Data has been written                        

Member Functions

The ostream class supports the following public member functions for formatting control:

  • width(int) - sets the field width to the integer received
  • fill(char) - sets the padding graphic symbol to the grapheme received
  • setf(...) - sets a formatting flag to the flag received
  • unsetf(...) - unsets a formatting flag for the flag received
  • precision(int) - sets the decimal precision to the integer received

width

The width(int) member office specifies the minimum width of the next output field:

                          // Field Width  // width.cpp   #include <iostream>  using namespace std;   int main() {      int attendance = 27;      cout << "1234567890" << endl;                          cout.width(ten);                          cout << omnipresence << endl;      cout << omnipresence << endl;  }                        
                            1234567890          27  27                        

width(int) applies only to the side by side field.  Note how the field width for the first display of attendance is 10, while the field width for the second display of attendance is only the minimum number of characters needed to display the value (2).

fill up

The fill up(char) fellow member role defines the padding character.  The output object inserts this grapheme into the stream wherever text occupies less infinite than the specified field width.  The default fill graphic symbol is ' ' (space).  To pad a field with '*''s, we add:

                          // Padding  // make full.cpp   #include <iostream>  using namespace std;   int primary() {      int attendance = 27;      cout << "1234567890" << endl;                          cout.make full('*');                          cout.width(10);      cout << omnipresence << endl;  }                        
                            1234567890  ********27                        

The padding grapheme remains unchanged, until nosotros reset it.

setf, unsetf - Format control

The setf() and unsetf() fellow member functions control formatting and alignment.  Their command flags include:

Control Flag  Consequence
ios::fixed  ddd.ddd
ios::scientific  d.ddddddEdd
ios::left  align left
ios::right  marshal right

The scope resolution (ios::) on these flags identifies them as part of the ios grade.

The default format in C++ is general format, which outputs information in the simplest, most succinct way possible (1.34, 1.345E10, ane.345E-xx).  To output a fixed number of decimal places, nosotros select fixed format.  To specify fixed format, nosotros pass the ios::fixed flag to setf():

                          // Stock-still Format  // fixed.cpp   #include <iostream>  using namespace std;   int main() {      double pi = iii.141592653;      cout << "1234567890" << endl;      cout.width(ten);                          cout.setf(ios::stock-still);                          cout << pi << endl;  }                        
                            1234567890    3.141593                        

Format settings persist until we modify them.  To unset fixed format, we laissez passer the ios::stock-still flag to the unsetf() member function:

                          // Unset Fixed Format  // unsetf.cpp   #include <iostream>  using namespace std;   int master() {      double pi = 3.141592653;      cout << "1234567890" << endl;      cout.width(x);                          cout.setf(ios::fixed);                          cout << pi << endl;                          cout.unsetf(ios::fixed);                          cout << pi << endl;  }                        
                            1234567890    three.141593  iii.14159                        

To specify scientific format, nosotros pass the ios::scientific flag to the setf() member function:

                          // Scientific Format  // scientific.cpp   #include <iostream>  using namespace std;   int main() {      double pi = 3.141592653;      cout << "12345678901234" << endl;      cout.width(14);                          cout.setf(ios::scientific);                          cout << pi << endl;  }                        
                            12345678901234    three.141593e+00                        

To turn off scientific format, we pass the ios::scientific flag to the unsetf() fellow member function.

setf, unsetf - Alignment

The default alignment is correct-justified.

To switch to left-justification, nosotros laissez passer the ios::left flag to the setf() member function:

                          // Left Justified  // left.cpp   #include <iostream>  using namespace std;   int main() {      double pi = 3.141592653;      cout << "1234567890" << endl;      cout.width(10);      cout.fill('?');                          cout.setf(ios::left);                          cout << pi << endl;  }                        
                            1234567890  iii.14159???                        

To switch off left-justification, nosotros pass the ios::left flag to the unsetf() member office:

                    cout.unsetf(ios::left);                  

precision

The precision() member function sets the precision of subsequent floating-point fields.  The default precision is half dozen units.  Full general, stock-still, and scientific formats implement precision differently.  General format counts the number of significant digits.  Scientific and stock-still formats count the number of digits following the decimal signal.

For a precision of ii under general format, we write

                          // Precision  // precison.cpp   #include <iostream>  using namespace std;   int main() {      double pi = 3.141592653;      cout << "1234567890" << endl;      cout.setf(ios::fixed);      cout.width(10);                          cout.precision(2);                          cout << pi << endl;  }                        
                            1234567890        3.14                        

The precision setting applies to the output of all subsequent floating-signal values until we change it.

Manipulators

The C++ linguistic communication defines manipulators that are elegant alternatives to fellow member part calls.  These manipulators are operands for the extraction and insertion operators.  Manipulators that don't accept any argument do not include parentheses and are divers in <iostream>.  Those that have an argument include parentheses and are divers in <iomanip>.  That is, we must include <iomanip> whenever we utilise manipulators that take an argument.

Input Manipulators

The manipulators of input objects are listed below:

Manipulator Consequence
skipws  skip whitespace
noskipws  plough off skip whitespace
setw(int)  fix the field width for next input (strings merely)

The argument to setw() should be one more than than the maximum number of input bytes to exist read.  Note that the setw() manipulator is an alternative to get(char*, int), just setw() skips leading whitespace unless we turn off skipping.

In one case a manipulator has modified the format settings of an input object, those settings remain modified.

We may combine manipulators with input variables directly to form chemical compound expressions.  For example,

                          // Input Manipulators  // manipulator.cpp   #include <iostream>  #include <iomanip>  using namespace std;   int primary( ) {      char a[5], b[2], c, d[7];      cout << "Enter : ";      cin >> setw(5) >> a >>             setw(2) >> b >> noskipws >>             c >> skipws >> d;      cout << "Stored '" << a <<              "' & '" <<  b <<              "' & '" << c <<              "' & '" << d << "'" << endl;   }                        
                            Enter :     abcde          fgh     Stored 'abcd' & 'due east' & ' ' & 'fgh'                        

Output Manipulators

The manipulators of output objects are listed below:

Manipulator Effect
stock-still  output floating-point numbers in fixed-indicate format
scientific  output floating-point numbers in scientific format
left  left justify
right  right justify
endl  output end of line and flush the buffer
setprecision(int)  set the precision of the output
setfill(int)  set the fill grapheme for the field width
setw(int)  set the field width for the next output operand just
setbase(int)  fix the base of operations of the number system for int output
flush  flush the output buffer

Manipulators (except for setw(i), which only modifies the format setting for the next object) modify the format settings until we change them.

For example,

                          cout << fixed << left << setw(5) <<         setprecision(1) << 12.376 <<         setprecision(five) << 12.376 <<         endl;                        
                            12.4 12.37600                        

Reference Example

The following program produces the output listed on the right

                          #include <iostream>  #include <iomanip>  using namespace std;   int chief( ) {      /* integers */      cout << "\n* ints *\north"      << "1234567890\n"      << "----------\n"      << 4321 << '\due north'      << setw(7) << 4321 << '\due north'      << setw(vii) << setfill('0') << 4321 << setfill(' ')<<'\n'       << setw(7) << left << 4321 << correct << '\n';      /* floats */      cout << "\n* floats *\due north"      << "1234567890\northward"      << "----------\n"      << 4321.9876546F << '\n';      /* doubles */      cout << "\n* doubles *\n"      << "1234567890\n"      << "----------\northward"      << fixed << iv.9876546 << '\n'      << setw(7) << setprecision(3) << iv.9876546 << '\northward'      << setw(seven) << setfill('0') << 4.9876546 << '\north'      << setw(7) << left << 4.9876546 << right << '\n';      /* characters */      cout << "\n* chars *\due north"      << "1234567890\n"      << "----------\n"      << 'd' << '\n'      << int('d') << '\due north';  }                        
                            * ints *  1234567890  ----------  4321     4321  0004321  4321   * floats *  1234567890  ----------  4321.99   * doubles *  1234567890  ----------  iv.987655    4.988  004.988  4.98800   * chars *  1234567890  ----------  d  100                        

Notes:

  • a double or a bladder rounds to the requested precision
  • char information displays in either character or decimal format
    to output its numeric code, we bandage the value to an int (the value output for 'd' here is its ASCII value).

Land

The ios base course defines public member functions that report or change the state of istream and ostream objects.  These member functions include:

  • skilful() - the adjacent operation might succeed
  • fail() - the next operation volition fail
  • eof() - end of data has been encountered
  • bad() - the data may be corrupted
  • clear() - reset the state to adept

For convenient input processing, we should bank check the state of the input object every fourth dimension information technology extracts a sequence of bytes from the input buffer.  If the object has encountered an invalid character, the object will fail and go out that invalid character in the input buffer and the fail() member role will return true.

Before a failed object can go on extracting data from the input buffer, nosotros must clear the object of its failed country.  The clear() function resets the land of the object to skillful:

                    if(cin.fail()) {            // checks if cin is in a failed state      cin.clear();            // clears state to allow further extraction       cin.ignore(2000, '\n'); // clears the input buffer  }                  

The following department provides a complete example.

Robust Validation

Robust validation enhances the friendliness of any application that processes input.  The state functions of the iostream classes help us validate input robustly.  Robust validation checks the input object's state after each extraction to ensure that the object has converted the sequence of bytes into a value and that that converted value is valid and within admissible bounds.  Robust validation rejects invalid input and out-of-spring values, resetting any failed land and requesting fresh input as necessary from the user.

getPosInt

To extract a positive int that is not greater than max from the standard input device, we write

                    // getPosInt extracts a positive integer <= max  // from standard input and returns its value  //  int getPosInt(int max) {      int value;      int keepreading;       keepreading = 1;      practice {          cout << "Enter a positive integer (<= " << max << ") : ";           cin  >> value;           if (cin.fail()) {   // check for invalid character              cerr << "Invalid graphic symbol.  Attempt Again." << endl;              cin.clear();              cin.ignore(2000, '\n');          } else if (value <= 0 || value > max) {              cerr << value << " is outside the range [1," <<                   max << ']' << endl;              cerr << "Invalid input.  Attempt Once again." << endl;              cin.ignore(2000, '\n');                    // you may cull to omit this branch          } else if (char(cin.go()) != '\n') {              cerr << "Trailing characters.  Endeavor Again." << endl;              cin.ignore(2000, '\north');                    } else              keepreading = 0;      } while(keepreading == 1);       return value;  }                  

File Stream Classes

The ios inheritance bureaucracy includes three derived classes specifically designed for processing file streams.  These classes manage the communications betwixt file streams containing eight-bit bytes and organization memory.

full ios hierarchy

The fstream system header file defines its classes in the std namespace:

#include <fstream>

The fstream classes include:

  • ifstream - processes input from a file stream
  • ofstream - processes output to a file stream
  • fstream - processes input from and output to a file stream

These classes admission a file stream through separate input and output buffers.

Extraction and Insertion Operator Overloads

The standard library overloads the extraction and insertion operators for the cardinal types.  Nosotros overload these operators for fstream objects as left operands and custom types as right operands.

Fundamental Types

For cardinal types run into the chapter entitled Input and Output Operators.

Custom Types

Typicall', custom types require separate overloads of both extraction and insertion operators.

While reading standard input involves prompting the suer, reading a file does not require whatever prompts.  The extraction operator for file input objects excludes prompts.  Since writing to a file matches the convention for subsequent reading from that file, the output to a file generally differs from the more than decorated output to be read by the user.  Moreover, since the insertion operator that takes an ostream object as its left operand class is a templated function and the ofstream class is a class derived from the ostream class, ambiguities arise with direct overloading of the operator for a custom blazon.  One way to avoid these ambiguities is to define a divide file class for the custom blazon and overload the insertion operator for that file class.

The file related additions are highlighted in the listings below.

The header file for the Student class includes the definition of a StudentFile grade that overloads the insertion operators for an ofstream object that receives the Student grade:

                    // Student.h   #include <iostream> // for std::ostream, std::istream                    #include <fstream>  // for std::ifstream                    const int NG = 13;                    class StudentFile;                    class Pupil {      int no;      bladder grade[NG];      int ng;  public:      Student();      Educatee(int);      Student(int, const float*, int);      void read(std::istream&);                    void read(std::ifstream&);                    void display(std::ostream& os) const;                    void display(StudentFile& os) const;                    };   std::istream& operator>>(std::istream& is, Pupil& s);  std::ostream& operator<<(std::ostream& os, const Educatee& southward);                    std::ifstream& operator>>(std::ifstream& is, Student& s);   class StudentFile {    public:      std::ofstream f;      StudentFile(const char*);      StudentFile& operator<<(char);      StudentFile& operator<<(int);      StudentFile& operator<<(float);      void close(); };   StudentFile& operator<<(StudentFile& os, const Pupil& s);                  

The implementation file overloads the file extraction and insertion operators for our Educatee class and defines the insertion operator for StudentFile objects every bit left operands and fundamental types as right operands:

                    // Student.cpp   #include "Student.h"   Educatee::Student() {      no = 0;      ng = 0;  }   Educatee::Educatee(int n) {      *this = Student(north, nullptr, 0);  }   Student::Pupil(int sn, const float* chiliad, int ng_) {      bool valid = sn > 0 && k != nullptr && ng_ >= 0;      if (valid)          for (int i = 0; i < ng_ && valid; i++)              valid = k[i] >= 0.0f && g[i] <= 100.0f;       if (valid) {          // take the client's information          no = sn;          ng = ng_ < NG ? ng_ : NG;          for (int i = 0; i < ng; i++)              course[i] = g[i];      } else {          *this = Student();      }  }   void Student::read(std::istream& is) {      int no;          // will hold the educatee number      int ng;          // volition concur the number of grades      float grade[NG]; // will agree the grades       std::cout << "Student Number : ";      is >> no;      std::cout << "Number of Grades : ";      is >> ng;      if (ng > NG) ng = NG;      for (int i = 0; i < ng; i++) {          std::cout << "Course " << i + 1 << " : ";          is >> grade[i];      }       // construct a temporary Student      Student temp(no, grade, ng);      // if data is valid, copy temporary object into current object      if (temp.no != 0)          *this = temp;  }                    void Student::read(std::ifstream& is) {      int no;          // volition agree the student number      int ng;          // will concord the number of grades      float form[NG]; // will hold the grades       is >> no;      is >> ng;      if (ng > NG) ng = NG;      for (int i = 0; i < ng; i++) {          is >> class[i];      }       // construct a temporary Student      Student temp(no, grade, ng);      // if data is valid, copy temporary object into electric current object       if (temp.no != 0)          *this = temp;  }                    void Pupil::brandish(std::ostream& bone) const {      if (no > 0) {          os << no << ":\n";          os.setf(std::ios::fixed);          bone.precision(two);          for (int i = 0; i < ng; i++) {              os.width(half dozen);              os << form[i] << std::endl;          }          os.unsetf(std::ios::fixed);          os.precision(6);      } else {          os << "no data available" << std::endl;      }  }                    void Student::display(StudentFile& os) const {      os << no << '\n';      os << ng << '\north';      for (int i = 0; i < ng; i++)          os << grade[i] << '\northward';  }                    std::ostream& operator<<(std::ostream& os, const Student& s) {      s.display(os);      render os;  }   std::istream& operator>>(std::istream& is, Student& s) {      s.read(is);      render is;  }                    std::ifstream& operator>>(std::ifstream& is, Student& s) {      s.read(is);      render is;  }   StudentFile& operator<<(StudentFile& f, const Student& s) {      s.display(f);      return f;  }   StudentFile::StudentFile(const char* filename) : f(filename) {}   StudentFile& StudentFile::operator<<(char c) {      f << c;      return *this;  }   StudentFile& StudentFile::operator<<(int i) {      f << i;      return *this;  }   StudentFile& StudentFile::operator<<(float v) {      f << 5;      return *this;  }   void StudentFile::close() {      f.shut();  }                  

Note the definitions of the read() and display() fellow member functions overloaded for file input and output respectively.

The client file that uses this upgraded Student class creates the file objects, writes to them and reads from them:

                          // Custom File Operators  // customFile.cpp   #include <iostream>  #include "Pupil.h"   int main ( ) {      Student harry;       std::cin >> harry;      std::cout << harry;       StudentFile studentFile("Student.txt");      studentFile << harry;      studentFile.close();       std::ifstream inFile("Pupil.txt");      inFile >> harry;      std::cout << harry;  }                        
                            Student Number : 1234   Number of Grades : 3  Form 1 : 56.7  Grade 2 : 78.ix  Grade three : 85.iv  1234:   56.70   78.90   85.forty  1234:   56.lxx   78.90   85.40                        

The records written to the Student.txt file by this programme are:

                    1234  iii  56.7  78.ix  85.4                  

Prissy to Know

Open-Mode Flags

To customize a file object'southward connection mode nosotros apply combinations of flags passed every bit an optional second argument to the object'due south constructor or its open() member function.

The flags defining the connection mode are:

  • std::ios::in open for reading
  • std::ios::out open for writing
  • std::ios::app open for appending
  • std::ios::trunc open up for writing, simply truncate if file exists
  • std::ios::ate motility to the finish of the file once the file is opened

Practical combinations of these flags include

  • std::ios::in|std::ios::out open up for reading and writing (default)
  • std::ios::in|std::ios::out|std::ios::trunc open for reading and overwriting
  • std::ios::in|std::ios::out|std::ios::app open up for reading and appending
  • std::ios::out|std::ios::trunc open for overwriting

The vertical bar (|) is the chip-wise or operator.

The Defaults

The default combinations for no-argument and 1-argument constructors are:

  • ifstream - std::ios::in - open for reading
  • ofstream - std::ios::out - open for writing
  • fstream - std::ios::in|std::ios::out - open for reading and writing

The Logical Negation Operator

The standard library overloads the logical negation operator (!) as an culling to the fail() query.  This operator reports true if the latest operation has failed or if the stream has encountered a serious error.

Nosotros can invoke this operator on any stream object to check the success of the most recent activity:

                          if (fin.fail()) {      std::cerr << "Read error";      fin.clear();  }                        
                          if (!fin) {      std::cerr << "Read fault";      fin.clear();  }                        

The operator practical directly to a file object returns the state of the connexion:

                    #include <iostream>  #include <fstream>   int primary() {      std::ofstream fout("output.txt");  // connects fout to output.txt                                          // for writing      if (!fout) {          std::cerr << "File is not open" << std::endl;      } else {          std::cout << "File is open" << std::endl;      }  }                  

Rewinding a Connectedness

istream, fstream

To rewind an input stream nosotros call:

  • istream& seekg(0) - sets the current position in the input stream to 0

ostream, fstream

To rewind an output stream nosotros telephone call:

  • ostream& seekp(0) - sets the current position in the output stream to 0

Premature Closing

To shut a file connection earlier the file object has gone out of scope, we telephone call the close() fellow member part on the object:

                    // Concatenate Two Files  // concatenate.cpp   #include <fstream>   int main() {      std::ifstream in("src1.txt");    // open 1st source file      std::ofstream out("output.txt"); // open destination file        if (in) {          while (!in.eof())              out << in.get();        // byte past byte re-create          in.clear();                    in.close();                    // shut 1st source file      }       in.open("src2.txt");            // open 2nd source file       if (in) {          while (!in.eof())              out << in.get();        // byte by byte re-create          in.clear();      }  }                  

Writing to and Reading from the Same File

The fstream course supports both reading and writing operations.  An instance of this class can write to a file and read from that same file.

For instance, the following program produces the output shown on the right

                          // File Objects - writing and reading  // fstream.cpp   #include <iostream>  #include <fstream>   int primary() {       std::fstream f("file.txt",       std::ios::in|std::ios::out|std::ios::trunc);      f << "Line one" << std::endl;   // record i      f << "Line two" << std::endl;   // tape two      f << "Line 3" << std::endl;   // tape 3      f.seekp(0);                   // rewind output      f << "****";                  // overwrite       char c;      f.seekg(0);                   // rewind input      f << std::noskipws;           // don't skip whitespace      while (f.good()) {          f >> c;                   // read one char at a time          if (f.skilful())              std::cout << c;       // display the character      }      f.clear();                    // clear failed (eof) state   }                        
                            **** one  Line 2  Line 3                        

Summary

  • the extraction and insertion operators support cascading
  • get() and getline() read strings with whitespace
  • a field width setting simply holds for the side by side field
  • all not-field width settings persist until changed
  • precision has dissimilar meanings under full general, scientific, and stock-still formats
  • manipulators are the elegant alternative to member function based format settings
  • manipulators that accept arguments are divers in #include <iomanip>
  • a failed country must be cleared before processing can continue
  • the extraction and insertion operators are overloaded for file objects as left operands and fundamental types every bit correct operands
  • an input file object is an instance of an ifstream class
  • an output file object is an case of an ofstream class
  • we may overload the extraction and insertion operators for file objects as left operands and our class types as correct operands

Exercises

  • Experiment with get(), getline() and country on little programs of your own
  • Complete the Handout on Input and Output

finkbrinnowere1990.blogspot.com

Source: https://ict.senecacollege.ca/~oop244/pages/content/basic_p.html

0 Response to "C++ Read Single Character From File Skipws"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel