I/O


File I/O

Useful functions for istreams (which includes ifstreams and cin)

Example (from fileIO.cpp)

ifstream inFile("inFile.txt");
if (!inFile) {
    cerr << "Unable to open inFile.txt for reading" << endl;
    return 1;
}

ofstream outFile("outFile.txt");
if (!outFile) {
    cerr << "Unable to open outFile.txt for writing" << endl;
    return 1;
}

char ch;
while (inFile.get(ch)) {
    switch (ch) {
      case 'a':  case 'A': 
      case 'e':  case 'E': 
      case 'i':  case 'I': 
      case 'o':  case 'O': 
      case 'u':  case 'U':
          outFile << '*';
          break;
      default:
          outFile << ch;
    }
}

inFile.close();
outFile.close();

Example (from fileIO.cpp)

int countLines(string & fileName) {

    ifstream myFile(fileName.c_str());

    if (myFile) {      

        int count = 0;
--------------------------------------------------------------
        //VERSION 1: C style strings
        // uses a char array and member function getline()
        char line[100];
        while (!myFile.getline(line, 100).eof()) {
            count++;
            cout << "Line " << count << ": " << line << endl;
        }
--------------------------------------------------------------
        //VERSION 2: C++ style strings
        // uses a string object and free function getline()
        string line;
        while (!getline(myFile, line).eof()) {
            count++;
            cout << "Line " << count << ": " << line << endl;
        }
--------------------------------------------------------------
        myFile.close();   
        return count;

    } else {
        cerr << "Unable to open " << fileName 
             << " in countLines" << endl;
        myFile.close();
        return -1;
    }
}

Formatting output using manipulators

Need to #include <iomanip> (to use manipulators that take arguments)

Common manipulators

Example (from Cpp_IO.cpp)

int x = 1234;
double y = 8763.1415;

cout << left << setw(20) << x << " " 
     << right << setw(11) << setprecision(6) 
     << fixed << y << " " 
     << str << endl;

Output:

1234                 8763.141500 cs368

C-Style I/O

Standard I/O library (inherited from C): #include <cstdio>

Console I/O

File I/O

Never mix I/O libraries in a single program!

Example (from C_IO.cpp)

int x = 1234;
double y = 8763.1415;
char str[20] = "cs368";




printf("x is %d, y is %f, str is %s\n", x, y, str);


printf("%-20d %11.6f %s\n", x, y, str);
  
  
    


    
printf("Enter a number and a string: ");

scanf("%d %s", &x, str);