Useful functions for istreams (which includes ifstreams and cin)
in.eof()
in.get(ch)
in.unget()
in.peek()
in.ignore(n, delim)
in.getline(myString, n)
getline(in, myString)
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();
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;
}
}
Need to #include <iomanip> (to use manipulators that take arguments)
Common manipulators
left, right
setw( int )
setprecision( int )
fixed
scientific
boolalpha
noboolalpha
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
Standard I/O library (inherited from C): #include <cstdio>
Console I/O
To write to standard output, use
To read from standard input, use
File I/O
To write to a file, use
To read from a file, use
Never mix I/O libraries in a single program!
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);