CSCE 121 Chapter 11

From Notes
Jump to navigation Jump to search

« previous | Wednesday, October 6, 2010 | next »

Customizing Input/Output

There are many types of I/O

Every output has certain interpretations

Formats

  • Integer Values:
    • decimal
    • octal
    • hexadecimal
cout << dec << 1234 << "\t(decimal)\n"
     << hex << 1234 << "\t(hexadecimal)\n"
     << oct << 1234 << "\t(octal)\n";

These base modifiers stay in effect until explicitly changed otherwise.

showbase formats numbers appropriately (0x for hex, 0### for oct)


  • Floating Point Values:
    • general
    • scientific
    • fixed / precision
cout << 1234.56789 << "\t\t(general)\n"
     << fixed << 1234.56789 << "\t(fixed)\n"             // Default precision = 6
     << scientific << 1234.56789 << "\t(scientific)\n";
  • Fields (length of input)

setw(int n); sets width of field


File Handle Alternatives

ios_base::app append
ios_base::ate "at end" (open and seek to end)
ios_base::binary binary mode (use with caution; try to always use text)
ios_base::in reading
ios_base::out writing
ios_base::trunc truncate file to 0-length
ofstream ofs(name.c_str(), ios_base::trunc);
ifstream ifs(name.c_str(), ios_base::binary


Friday, October 8, 2010


Binary Files

int main() {
  vector<int> v;
  int i;

  // Read ints from binary file
  while (ifs.read(as_bytes(i), sizeof(int))) v.push_back(i);

  // Write ints to binary file
  for (unsigned i=0; i<v.size(); ++i)
    ofs.write(as_bytes(v[i]), sizeof(int));
  return 0;
}

Positioning in a filestream

(Please try not to use...)

fstream fs(name.c_str());  // open for reading and writing
char ch;

fs.seekg(5);  // move reading position ("g" = "get") to 5 (6th character)
fs >> ch;     // read and increment reading position (now 6)
fs.seekp(1);  // move writing position ("p" = "put") to 1 (2nd character)
fs << 'y';    // write and increment writing position (now 2)

String Streams

double str_to_double(string s) {
  istringstream is(s); // make a stream so we can read from s
  double d;
  is >> d;
  if (!is) error("double format error");
  return d;
}

Reading Type vs. Line

Read a string:

string name;
cin >> name;           // Input: Dennis Ritchie
cout << name << endl;  // Output: Dennis

Read a line:

string name;
getline(cin, name);   // Input: Dennis Ritchie
cout << name << endl; // Output: Dennis Ritchie

Reading characters skipping whitespace

char ch;
while (cin >> ch) {
  /* ... */
}

Reading characters including whitespace

char ch;
while (ch = cin.get()) {
  /* ... */
}

Built-in Character Tests

Function RegExp Description
isspace(c) (/ /) Whether char c is a space
isalpha(c) (/A-Za-z/) Alphabetic character
isdigit(c) (/0-9/) Numeric character
isupper(c) (/A-Z/) Uppercase alpha character (use toupper(s) to get uppercase string)
islower(c) (/a-z/) Lowercase alpha character (use tolower(s) to get lowercase string)
isalnum(c) (/a-z0-9/) Alpha-numeric