iostream

Author:宋方睿
Date:2011-11-25

Powered by rst2s5

Standard I/O Streams Library

images/iostream.gif images/BasicIOClasses.png

Four Basic Stream Objects

Format Flags

Format Flags -- ios::adjustfield

Format Flags -- ios::basefield

Format Flags -- ios::floatfield

Format Flags -- misc

Format Flags -- misc

istream

ios_base::iostate

istream::setstate

istream::operator>>

istream::operator>>

istream::get

istream::get

istream::get

Example

#include <iostream>
#include <fstream>
using namespace std;
int main () {
char c, str[256];
ifstream is;
cout << "Enter the name of an existing text file: ";
cin.get (str,256);
is.open (str); // open file
while (is.good()) // loop while extraction from file is possible
{
c = is.get(); // get character from file
if (is.good())
cout << c;
}
is.close(); // close file
return 0;
}

istream::getline

Example

#include <iostream>
int main()
{
using namespace std;
const int line_buffer_size = 100;
char buffer[line_buffer_size];
int line_number = 0;
while (cin.getline(buffer, line_buffer_size, ’n’) || cin.gcount()) {
int count = cin.gcount();
if (cin.eof())
cout << "Partial final line";
// cin.fail() is false
else if (cin.fail()) {
cout << "Partial long line";
cin.clear(cin.rdstate() & ̃ios::failbit);
} else {
count--;
// Don’t include newline in count
cout << "Line " << ++line_number;
}
cout << " (" << count << " chars): " << buffer << endl;
}
}

istream::ignore

istream::peek

Example

#include <iostream>
using namespace std;

int main () {
char c;
int n;
char str[256];
cout << "Enter a number or a word: ";
c=cin.peek();
if ( (c >= '0') && (c <= '9') )
{
cin >> n;
cout << "You have entered number " << n << endl;
}
else
{
cin >> str;
cout << " You have entered word " << str << endl;
}

return 0;
}

ios_base::width, ios::fill

Example

#include <iostream>
using namespace std;
int main ()
{
cout << 100 << endl;
cout.width(10);
cout << 100 << endl;
cout.fill('x');
cout.width(15);
cout << left << 100 << endl;
return 0;
}

Example

#include <iostream>
using namespace std;
int main ()
{
cout << setw(7) << 269 << endl;
cout << 269 << endl;
return 0;
}

ios_base::precision

Example

#include <iostream>
using namespace std;

int main () {
double f = 3.14159;
cout.unsetf(ios::floatfield); // floatfield not set
cout.precision(5);
cout << f << endl;
cout.precision(10);
cout << f << endl;
cout.setf(ios::fixed,ios::floatfield); // floatfield set to fixed
cout << f << endl;
return 0;
}

Thanks