To know about:
string class
iostream class
Remember that C came before C++,
and a goal of C++ is to be a superset of C.
Therefore, all things C need to still work,
including I/O.
C strings
From the C programming language,
(and still handled in C++)
A string is any array of characters
that
contains and ends with the null character ('\0').
The size of the array must be (at least)
1 + number of non-null characters in the string
Example:
"Hi!" (4 characters) -------------------------- | 'H' | 'i' | '!' | '\0' | --------------------------
Fun things to do with C strings
(provided by the cstring library)
#include <cstring> // prototypes int strlen(const char* str); char * strcpy(char* dest, const char* src); char * strcat(char* dest, const char* src); int strcmp(const char* str1, const char* str2);
NOT fun things to do with C strings
string class
the C++ string class
strings are mutable
(meaning that you can change them)
Part of the standard namespace,
but include the library anyway:
#include <string>
Fun things to do with strings:
use overloaded operators:
== != > >= < <= = []
Some class functions:
// prototypes
istream & getline(istream& is, string& str);
size_t find(const string& str, size_t pos=0)
const;
string substr(size_t pos=0, size_t n=npos)
const;
size_t length() const;
const char* c_str() const;
Note: size_t is an unsigned, integral type.
npos is the largest defined size_t value.
#include <string> string s = "One rat." cout << s << endl; s[4] = 'c'; cout << s << endl;
-------------------- | One rat. | One cat. |
The iostream class
input comes from standard input
and output goes to standard output
and
standard error
The iostream class includes
cin,
cout,
and cerr.
cin
Reads from standard input. For example:
cin >> x; cin >> a >> b;
Designed to skip white space
(spaces, tabs, newlines).
more on cin
Read one character at a time,
if the application needs it:
char ch = '\0';
char nextch;
cin.get(nextch);
while (nextch != '\n') {
ch = nextch;
cin.get(nextch);
}
cout << "Character before newline: "
<< ch << endl;
cout
Sends to standard output. For example:
cout << "There are " << count << " dogs." << endl;first does
( cout << "There are " )then does
( cout << count )then does
( cout << " dogs." )and finally does
cout << endl;
more on cout
Write one character at a time with put:
// one prototype ostream & put(char);
You can do:
char W = 'w'; cout.put(W);or
cout.put('w');
put is overloaded:
cout.put(65); // prints an 'A'
and with a little automatic conversion. . .
cout.put(66.4); // prints a 'B'
file I/O
#include <fstream>
Files must be opened.
Files ought to be closed.
Files can be read.
Files can be written to.
Inheritance chain for I/O
Input from a file:
ifstream infile("myfile");
if (infile) {
// file is open to read from
} else {
cout << "Opening failed.\n";
}
Constructor creates and opens the file.
File name is a C string!
(Convert a string object to a C string
with c_str())
Useful ifstream functions
void open(const char* filename,
ios_base::openmode mode = ios_base::in );
istream & get(char & ch); // get 1 character,
// placed into ch
int peek(); // returns value of next character,
// without removing it from the stream.
bool eof() // returns true if end of file
const; // encountered during previous operation
bool good() // returns true if none of the stream's
const; // error flags are set
bool fail() // returns true if error flags
const; // (other than end of file) are set
void clear(); // clears all error flags
Function getline() not included here,
as it comes from the string class.
/*
* Example showing file input and output
*
* Updated by Jim Skrentny for CS 368, Fall 2006
* Written by Rebecca Hasti for CS 368, Spring 2004
*/
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
/*
* countLines
*
* Counts the number of lines in the file with the given name.
* The lines are also echoed to standard output (along with the line number)
* If the file cannot be opened, -1 is returned.
*/
int countLines(string & fileName) {
ifstream myFile(fileName.c_str());
// Note conversion of string library object to C-style string using c_str
if (myFile) { // if the file was successfully opened
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(); // close the file now that we're done with it
return count;
} else {
cerr << "Unable to open " << fileName << " in countLines" << endl;
myFile.close();
return -1;
}
}
int main() {
// Open inFile.txt
ifstream inFile("inFile.txt");
if (!inFile) {
cerr << "Unable to open inFile.txt for reading" << endl;
return 1;
}
// Open outFile.txt
ofstream outFile("outFile.txt");
if (!outFile) {
cerr << "Unable to open outFile.txt for writing" << endl;
return 1;
}
// The following copies inFile.txt to outFile.txt, replacing
// each occurrence of a vowel (a, e, i, o, u) with a *
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;
}
}
// Close files when finished with them
inFile.close();
outFile.close();
// Now test the countLines function
string name = "inFile.txt";
int numLines = countLines(name);
cout << "File " << name << " has " << numLines << " lines" << endl;
return 0;
}
/*
* This is a very simple program which demonstrates how to access
* command line arguments. Try the following commands:
* g++ echoArgs.cpp
* a.out
* a.out 123 abcd
*
* Written by Rebecca Hasti for CS 368, Spring 2004
*/
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
cout << "Echoing command line arguments (one per line):" << endl;
for (int i = 0; i < argc; i++)
cout << argv[i] << endl;
return 0;
}
| Copyright © Karen Miller, 2007 |