12 Januari, 2010

Polymorphism


                Kemampuan sebuah variabel reference untuk merubah behavior sesuai dengan apa yang dipunyai object.
                polymorphism membuat objek-objek yang berasal dari subclass yang berbeda, diperlakukan sebagai objek-objek dari satu superclass. Hal ini terjadi ketika memilih method yang sesuai untuk diimplementasikan ke objek tertentu berdasarkan pada subclass yang memiliki method bersangkutan.

Untuk menjelaskan polymorphism, mari kita bahas sebuah contoh.

◦       Pada contoh sebelumnya, kita diberikan parent class yaitu Person dan subclassnya adalah Student, sekarang kita tambahkan subclass lainnya dari Person yaitu Employee

Dalam Java, kita dapat membuat referensi dari suatu superclass ke object dari subclassnya. Sebagai contoh,

public static main( String[] args ) {

   Person  ref;
   Student studentObject = new Student();
   Employee employeeObject = new Employee();
   ref = studentObject; //titik referensi Person kepada                          // sebuah object Student
}

misalnya, kita memiliki sebuah method getName dalam superclass Person. Dan kita meng-override method ini di kedua subclass yaitu Student dan Employee

public class Student {
   public String getName(){
        System.out.println(“Student Name:” + name);
        return name;
   }
}
public class Employee {
   public String getName(){
        System.out.println(“Employee Name:” + name);
        return name;
   }
}

◦       Kembali ke method utama kita, ketika kita mencoba memanggil method getName dari referensi Person ref, method getName dari object Student akan dipanggil.
◦       Sekarang, jika kita memberi ref kepada object Employee, maka method getName juga akan dipanggil

public static main( String[] args ) {
     Person  ref;
     Student studentObject = new Student();
     Employee employeeObject = new Employee();
     ref = studentObject; //titik referensi Person kepada object Student
     //getName dari class Student dipanggil
     String temp=ref.getName();
     System.out.println( temp );
     ref = employeeObject; //titik referensi Person kepada  object Employee
    
     //getName dari class Employee dipanggil 
     String temp = ref.getName();
     System.out.println( temp );
}

◦       Contoh lain yang menggambarkan polymorphism adalah ketika kita mencoba untuk passing reference kepada method
◦       jika kita memiliki sebuah method static printInformation yang menerima referensi Person sebagai parameter

                public static printInformation( Person p ){
                                     . . . .
     }

Sebenarnya kita dapat passing reference dari Employee dan Student kepada method printInformation selama kedua class tersebut merupakan subclass dari Person

public static main( String[] args )
{
        Student    studentObject = new Student();
        Employee   employeeObject = new Employee();
        printInformation( studentObject );
        printInformation( employeeObject );
}





Pewarisan (inheritance)


Semua class dalam Java, termasuk class yang membangun Java API, merupakan subclass dari superclass Object.

Superclass            
                class yang letaknya di atas class tertentu di dalam hierarki.
Subclass                
                class yang letaknya di bawah class tertentu    di dalam hierarki.

Keuntungan penggunaan Inheritance dalam OOP : Reusability
◦       Ketika behavior(method) dideklarasikan dalam superclass, behavior tersebut otomatis diwariskan ke seluruh subclass
◦       Jadi, Anda dapat meng-enkode method hanya sekali dan method tersebut dapat digunakan oleh seluruh subclass
◦       Sebuah subclass hanya perlu mengimplementasikan perbedaan antara dirinya sendiri dan parent-nya

◦       Untuk mengambil sebuah class, gunakan keyword extends.
◦       Untuk lebih jelasnya, mari buat class parent sederhana, misalkan kita mempunyai class parent bernama Person.

public class Person {
   protected String name;
   protected String address;
   /**
    * Default constructor 
    */
   public Person(){
         System.out.println(“Inside Person:Constructor”);
         name = ""; address = "";
   }
   . . . .
}

◦       Sekarang, kita buat class lain bernama Student
◦       Karena murid juga termasuk orang, kita putuskan untuk meng-extend class Person, sehingga kita dapat mewariskan semua properti dan method yang telah ada di class Person.
◦       Untuk itu, kita bisa menulis :

public class Student extends Person {
   public Student(){
         System.out.println(“Inside Student:Constructor”);
   }
   . . . .
}

◦       Untuk memperjelasnya, perhatikan kode dibawah ini,

public static void main( String[] args ){
   Student anna = new Student();
}

◦       Dalam kode ini, kita membuat sebuah object dari class Student. Hasil dari program adalah:

Inside Person:Constructor
Inside Student:Constructor




Function Template


Pertama - tama mari kita membahas tentang function template.Untuk itu marilah kita perhatikan contoh berikut.

template <class tipe>
void swap(tipe &a,tipe &b)
{
tipe c;
c = a;
a = b;
b = c;
}

Pada contoh diatas terdapat sebuah fungsi swap (menukar 2 buah variable) menggunakan template.. Untuk pemanggilan fungsi dilakukan seperti pemanggilan fungsi tanpa template. Untuk itu mari perhatikan penggalan perintah untuk menggunakan fungsi swap.

Contoh template dengan instance tipe int

void main(void)
{
int a,b;
a = 10;
b = 20;
swap(a,b); cout << a << “ “ << b << endl;
}

Contoh template dengan instance tipe float
void main(void)
{
float a,b;
a = 10.0;
b = 20.0;
swap(a,b); cout << a << “ “ << b << endl;
}

Contoh template dengan instance struct tTes
struct tTes
{
int a,b;
};
void main(void)
{
tTes a,b;
a.a = 10;
a.b = 20;
b.a = 30;
b.b = 40;
swap(a,b);
cout << a.a << " " << a.b << " " << b.a << " " << b.b;
}

Dapat dilihat , dengan menggunakan template kita telah menghemat waktu untuk menulis fungsi Pada fungsi swap diatas , juga tidak menutup kemungkinan untuk menukar 2 buah kelas.
Pada contoh diatas fungsi tidak akan bekerja jika variable yang ditukar berbeda tipe . Walaupun kekerabatannya cukup dekat . Anda tidak bisa menukar tipe int (16bit) dengan tipe short (16 bit). Ini terkait dengan pendeklarasian template pada fungsi swap.

template <class tipe>
void swap(tipe &a,tipe &b)

Pada pendeklarasian fungsi swap dapat dilihat bahwa formal parameter a sama dengan formal parameter b . Oleh sebab itu sudah seharusnya tipe pada actual parameter pun harus sama. Untuk contoh fungsi swap diatas sebaiknya anda tidak menggunakan type-casting untuk mengatasi masalah diatas. Mengingat fungsi swap diatas dikirim by reference . (Yang mana dalam pengiriman fungsi menggunakan reference berkaitan dengan pointer). Tentu saja ukuran dari variable menjadi sangat penting karena kita telah merubah ukuran dari variable (type casting) bisa saja terjadi hasil yang tak terduga . Walupun kadang – kadang memberikan hasil yang benar. Kecuali jika ukuran kedua tipe variable tersebut benar - benar sama , anda dapat menggunakan type–casting dalam hal ini.
Untuk mendefiniskan lebih dari satu type pada template anda dapat menggnakan koma sebagai pemisah
contoh :
Template dengan 2 buah tipe
template <class tipe1,class tipe2>

06 Desember, 2009

Friend Function

Concept 
When a function needs to operate on private data in objects two different classes, the function can be declared as a friend in each of the classes, taking objects of the two classes as arguments.
// A common friend function to exchange the private values of two classes
#include <iostream.h>
class A;
class B; 

class A 
{ 
  private:
    int value1;
  public: 
    void in(int a)
    {
       value1=a;
    }
   void display()
   {
       cout<< value1;
   }
   friend void exchange(A&, B&); 
 }; 

class B 
{ 
   private:
     int value2;
   public:
     void in(int a) 
     {
        value2=a; 
     } 
     void display()
     {
        cout<< value2; 
     }
     friend void exchange (A&, B&); 
}; 

void exchange(A& x, B& y) 
{
   int temp=x.value1;
   x.value1=y.value2; 
   y.value2=temp; 
} 

int main()
{ 
   A obj1;
   B obj2;
   obj1.in(1000);
   obj2.in(2000);
   cout<<"\n Before";
   obj1.display();
   obj2.display();
   cout<<"\n After";
   exchange(obj1, obj2);
   obj1.display();
   obj2.display();
   return 0;
}


Example
The following is an example of friend function's usage. The function show() is a friend of classes A and B which is used to display the private members of A and B. Instead of writing a separate function in each of the classes only one friend function can be used to display the data items of both the classes.
//Example - 1
#include<iostream.h>  
using namespace std; 

class B; // Forward declaration of class B in order for example to compile 

class A 
{
  private: 
    int a;
  public: A() 
  { 
    a=0; 
  } 
  friend void show(A& x, B& y); 
}; 

class B 
{ 
   private: 
     int b; 
   public:
    B()
    {
      b=6;
    }
    friend void show(A& x, B& y);
}; 
void show(A& x, B& y) 
{
   cout << "A::a=" << x.a << endl;
   cout << "B::b=" << y.b << endl;
}

int main() 
{
   A a;
   B b;
   show(a,b);
} 

//Example - 2
#include<iostream.h>
using namespace std; 

class B; // Forward declaration of class B in order for example to compile 

class A 
{
  private:
    int a;
  public: 
    A() 
    {
       a=0; 
     } 
     void show(A& x, B& y); 
}; 

class B 
{
   private:
     int b;
   public:
     B()
     {
       b=6;
     }
     friend void A::show(A& x, B& y);
};

void A::show(A& x, B& y)
{
   cout << "A::a=" << x.a << endl;
   cout << "B::b=" << y.b << endl;
}

int main()
{
   A a;
   B b;
   a.show(a,b);
   return 0;
}

24 Oktober, 2009

constructor

Constructor merupakan suatu method yang akan memberikan nilai awal pada saat suatu objek dibuat. Pada saat program dijalankan, constructor akan langsung memberikan nilai awal pada saat perintah new, membuat suatu objek
Pada saat kita bekerja dengan constructor, hal mendasar yang perlu diperhatikan, yaitu:

1. Nama Constructor sama dengan nama Class.
2. Tidak ada return type yang diberikan kedalam Constructor Signature.
3. Tidak ada return stetement, didalam tubuh constructor.

class Lat801
{
float nilakhir;

Lat801(int nilai_akhir)
{
nilakhir = nilai_akhir;
}

public String grade()
{
String nilgrade;
if(nilakhir >= 80)
nilgrade = "A";
else if(nilakhir >= 68)
nilgrade = "B";
else if(nilakhir >= 56)
nilgrade = "C";
else if(nilakhir >= 49)
nilgrade = "D";
else
nilgrade = "E";

return nilgrade;
}

public void cetak()
{
System.out.println("Grade Nilainya = " + grade());
}

public static void main(String[] args)
{
Lat801 hasil = new Lat801(67);
hasil.cetak();
}
}


Constructor Overloading

Overloading adalah suatu cara membuat lebih dari constructor pada suatu class. Supaya pengaksesan constructor tersebut lancar, maka sebagai pembedanya adalah tipe parameter dan atau jumlah parameternya

class Lat802
{
float nilakhir, a;

Lat802(int nilai_akhir){
nilakhir = nilai_akhir;
}

Lat802(int nil1, int nil2){
nilakhir = ab + ac;
}

public String grade()
{
String nilgrade;
if(nilakhir >= 80)
nilgrade = "A";
else if(nilakhir >= 68)
nilgrade = "B";
else if(nilakhir >= 56)
nilgrade = "C";
else if(nilakhir >= 49)
nilgrade = "D";
else
nilgrade = "E";

return nilgrade;
}

public void cetak()
{
System.out.println("Grade Nilainya = " + grade());
}

public static void main(String[] args)
{
Lat802 hasil = new Lat802(67);
hasil.cetak();
Lat802 hasilnya = new Lat802(45, 35);
hasilnya.cetak();
}
}


Method Overloading

Method Overloading adalah suatu cara membuat lebih dari method pada suatu class. Supaya pengaksesan method tersebut lancar, maka sebagai pembedanya adalah tipe parameter dan atau jumlah parameternya. Untuk lebih jelasnya anda bisa lihat program dibawah ini :

class Perhitungan
{
static public int hitung(int a, int b)
{
return a + b;
}

static public double hitung(double a, double b, double c)
{
return (a + b)/c;
}
}

public class Lat803
{
public static void main(String[] args)
{
Perhitungan Ngitung = new Perhitungan();

int hitung;
double bagi;

hitung = Ngitung.hitung(4, 8);
bagi = Ngitung.hitung(55, 69, 2);

System.out.println("Hasil Perhitungan = " + hitung);
System.out.println("Hasil Pembagian = " + bagi);
}
}

konsep encapsulation

Encapsulation merupakan salah satu konsep yang sangat penting dalam pemrograman berorientasi obyek.
Konsep dasarnya sangat sederhana, yaitu memproteksi setiap atribut dari suatu class. Dalam hal ini atribut dari suatu class tidak boleh diakses secara langsung dari luar class. Maka tidak mengherankan bila setiap atribut lalu diberi visibility private. Lalu bagaimana bila suatu saat nilai dari atribut tersebut ingin diakses ataupun ingin diubah? Jawabannya sederhana saja, dengan menggunakan accessor dan mutator. Untuk melakukan akses terhadap nilai dari suatu atribut kita dapat menggunakan accessor, sedangkan untuk menlakukan pengubahan terhadap nilai dari suatu atribut kita dapat menggunakan mutator. Untuk lebih jelasnya dapat melihat contoh sederhana berikut ini.

//class dengan nama Kemeja
class Kemeja {
//atribut warna bertipe data String
private String warna;
//mutator untuk atribut warna
public void setWarna(String warna) {
this.warna = warna; //penggunaan kata kunci this
}
//accessor untuk atribut warna
public String getWarna() {
return warna;
}
}

Accessor secara konvensi akan selalu diawali dengan kata get dan diikuti dengan nama atribut yang akan diakses. Oleh karenanya accessor seringkali dikenal dengan nama getter.
Sedangkan mutator secara konvensi akan selalu diawali dengan kata set dan diikuti dengan nama atribut yang akan diubah nilainya. Oleh karenanya mutator seringkali dikenal dengan nama setter.
Pada setter seringkali juga digunakan kata kunci this. Penggunaan kata kunci this pada setter ini dibutuhkan ketika ada kesamaan antara nama parameter yang digunakan dengan nama atribut yang akan diubah nilainya. Kata kunci this digunakan untuk membedakan antara nama atribut dengan nama parameter.
Lalu apa konsekuensi dari penerapan encapsulation ini? Konsekuensinya sederhana saja. Misalkan kita akan membuat suatu objek dari class Kemeja.

Kemeja kemejaku = new Kemeja();

Maka ketika kita ingin memberi nilai "hijau" pada atribut kemejaku, kita tidak bisa melakukan hal semacam ini

kemejaku.warna = "biru";

Mengapa? Karena visibility dari atribut warna adalah private sehingga atribut tersebut tidak dapat diakses dari luar class. Yang dapat kita lakukan adalah dengan menggunakan setter seperti berikut ini

kemejaku.setWarna("biru");

Dan bila kita ingin mencetak nilai atrubut warna, kita dapat melakukannya dengan cara

System.out.println(kemejaku.getWarna());

20 Oktober, 2009

Typedef

typedef adalah keyword untuk membuat suatu tipe data baru dari tipe data yang sudah ada, atau lebih mudah disebut membuat alias.
typedef : type definition

jadi untuk membuat nama lain dari suatu tipe data, gunakan typedef.

misal, kita ingin membuat nama lain dari tipe data integer

typedef int intku;

maka kita bisa membuat variabel dengan tipe data integer dengan menggunakan intku.

intku nilai;
nilai = 10;

jadi variabel nilai adalah bertipe integer juga, dengan proses pembuatan menggunakan nama alias intku.

struct mahasiswa {
char nim[10];
}mhs, mhs2;

begitu juga dengan struct. 'struct mahasiswa' diatas adalah satu tipe data baru buatan kita sendiri. agar kita tidak terlalu panjang mendefinisikan variabel, lengkapi saja dengan typedef sehingga proses pembuatan variabel bisa langsung dengan nama struct tanpa dilengkapi keyword 'struct'

versi 1:
struct mahasiswa {
char nim[10];
};

//deklarasi variabel
struct mahasiswa mhs;

versi 2:
typedef struct mahasiswa{
char nim[10];
};

atau

typedef struct {
char nim[10];
}mahasiswa;

//deklarasi variabel
mahasiswa mhs;

Nested Struct

Di dalam sebuah struct dapat dimungkinkan terdapat sebuah struct lagi. Jadi hal ini dapat diartikan struct di dalam struct. Hampir mirip nested loop, yaitu for di dalam for.

Contoh :

struct tanggal {
int hari;
int bulan;
int tahun;
};

struct karyawan {
char NIP [10];
char nama [20];
struct tanggal tgl_masuk;
float gaji;
};


13 Oktober, 2009

The 11 Standard Template Library (STL) Headers

Headers for the STL "sequence containers"

<deque>

This header provides a double-ended queue container, with fast insertion and deletion at both ends and (somewhat counterintuitively to the abstract notion of queueness) direct access to any element.

<list>

This header provides a sequence container with fast performance when adding elements to, or removing elements from, any point in the sequence, but with only sequential access to any particular element.

<vector>

This header provides the vector container, which is best thought of as a generalized array, capable of "growing and shrinking" as the occasion demands. Vectors provide fast insertion and deletion at one end, and direct access to any element.

Headers for the STL "associative containers"

<map>

This header provides map and multimap classes which store key-value pairs. The map requires unique keys, but the multimap permits duplicate keys.

<set>

This header provides set and multiset classes which store keys. The set can store only unique keys, but the multiset permits duplicate keys.

Headers for the STL "container adaptors"

<queue>

This header provides containers which are actually "adapted" sequential containers and provide the usual FIFO behavior of a standard queue structure, as well as "priority queue" behavior.

<stack>

This header provides a container which is actually one of the above containers "adapted" to provide the usual LIFO behavior of a stack structure.

Headers for the STL algorithms

<algorithm>

This header provides a large number (about 70, depending on how you count) generic algorithm function templates for operating on iterators, as well as some other objects such as "function objects" that help algorithms to perform their tasks. It is part of the genius, power and flexibility of the STL that these algorithms do not operate on containers directly, but on iterators that point to containers. This means that under quite general conditions, the same algorithm can operate on several different containers, and in a variety of ways, which is, of course, the whole point of "generic programming".

<numeric>

This header declares a small number (four) of function templates specifically for numerical algorithms.

Headers for the STL iterators and function objects

<iterator>

This header provides classes and templates for defining and using iterators, though it does not have to be included if you are just using one or more of the sequential and/or associative containers and their associated iterators, since those iterators will be available from the container classes themselves.

<functional>

This header defines several function objects. These may also be called functionals, or functors. A function object is an object of a class that implements operator(). This permits the function object to be "called", using the same syntax as a function, to help an algorithm perform its task. But, because it is an object, it is more versatile than a function.

Miscellaneous STL headers

<memory>

This header declares functions and class templates for allocating and using memory. The average programmer will not need to include this header, since the default container "allocators" are perfectly adequate most of the time. Programmers who are developing their own containers, iterators and algorithms will be more inclined to find a use for what's in this header.

<utility>

This header declares the pair<> template, which is essential when using maps and multimaps, but also finds many uses in everyday programming. Though it may or may not be of interest to the average programmer, this header also defines the rel-ops namespace, which in turn defines relational operators in terms of == and <.

The 10 "stream-related" headers

<fstream>

This header declares some classes and other types for performing I/O with external files, as well as member functions for opening and closing files and testing whether a file is open. Under this header, class names are shown as they would appear in a typical object declaration, and member functions are presented in "typical usage" format.

fstream file;
Declare an fstream object file that can be used for reading input and/or writing output
fstream file(c_string_value);
Declare an fstream object file, connect it to the physical file whose name is in the C-string c_string_value, and open it for reading input and/or writing output
fstream file(c_string_value, openmode_value);
Declare an fstream object file, connect it to the physical file whose name is in the C-string c_string_value, and open it using the specific value of type openmode specified in openmode_value [See under <ios> for the definition of the openmode type.]

ifstream inFile;
Declare an ifstream object inFile that can be used for reading input
ifstream inFile(c_string_value);
Declare an ifstream object inFile, connect it to the physical file whose name is in the C-string c_string_value, and open it for reading input
ifstream inFile(c_string_value, openmode_value);
Declare an ifstream object inFile, connect it to the physical file whose name is in the C-string c_string_value, and open it using the specific value of type openmode specified in openmode_value [See under <ios> for the definition of the openmode type.]

ofstream outFile;
Declare an ofstream object outFile that can be used for writing output
ofstream outFile(c_string_value);
Declare an ofstream object outFile, connect it to the physical file whose name is in the C-string c_string_value, and open it for writing output
ofstream outFile(c_string_value, openmode_value);
Declare an ofstream object outFile, connect it to the physical file whose name is in the C-string c_string_value, and open it using the specific value of type openmode specified in openmode_value [See under <ios> for the definition of the openmode type.]

In each of the three groupings immediately above, the first form just declares a file stream object, while the other two both declare a file stream object and open a physical file attached to that object. However, if the first form is used to declare a file stream object, then the actual file has to be opened later via a call to the open function, which is what the two forms shown below provide.

anyFileStream.open(c_string_value)
Connect the file stream object anyFileStream with the physical file whose name is in the C-string c_string_value, open it in a default mode which will depend on the actual class type of anyFileStream, and return the this pointer if successful or a NULL pointer if unsuccessful
anyFileStream.open(c_string_value, openmode_value)
Connect the file stream object anyFileStream with the physical file whose name is in the C-string c_string_value, open it in a mode determined by openmode_value, and return the this pointer if successful or a NULL pointer if unsuccessful [See under <ios> for the definition of the openmode type.]

anyFileStream.is_open()
Return true if the file stream object anyFileStream is open, and otherwise false
anyFileStream.close()
Close the physical file associated with the file stream object anyFileStream, and disconnect the two

<iomanip>

This header declares the I/O manipulators that take parameters. They are presented in "typical usage" format.


The following three manipulators provide one mechanism for setting (or "unsetting") the format-state flags. There are member functions under <ios> that accomplish the same purpose.

setbase(int_value)
Set the base (or conversion radix) for a stream to int_value, which must be one of the following values, since any other value will be interpreted as 0: 10 (for decimal), 8 (for octal), or 16 (for hex)
setiosflags(fmtflags_value)
Set the format-state flags specified explicitly in fmtflags_value and leave the remaining flags unchanged (equivalent to stream.setf(fmtflags_value) under <ios>) [See <ios> as well for the definition of the fmtflags type.]
resetiosflags(fmtflags_value)
Clear the format-state flags specified explicitly in fmtflags_value and leave the remaining flags unchanged (equivalent to stream.unsetf(fmtflags_value) under <ios>) [See <ios> as well for the definition of the fmtflags type.]

The next three manipulators provide one mechanism for setting the format-state parameters. There are member functions under <ios> that accomplish the same purpose.

setfill(int_value)
Set the "fill" format-state parameter that determines the "fill character" when numerical values are output to the character whose internal integer code is int_value
setprecision(int_value)
Set the "precision" format-state parameter to int_value places for floating-point values
setw(int_value)
Set the "width" format-state parameter to int_value

<ios>

This header declares the classes, types, and manipulators that form the foundation of the C++ I/O library. A class called ios_base is the base class for all I/O stream classes, and a class template called basic_ios derives from ios_base and declares the behavior that is common to all I/O streams.
All manipulators and member functions in this subsection are presented in "typical usage" format.


The types in the following list are referred to in various places later under this header and elsewhere on this web page. When you encounter such a reference (as the type of a function parameter, say), you may want to look back here at one of these type definitions to verify that a parameter of that type makes sense for that function (for example).
This list gives only a high-level description of each typedef, which is further constrained by the fact that each actual type is implementation-defined. For further information, check this site's page on C++ Input/Output. The ellipsis (...) that appears in each list item is the placeholder for the actual type name.

fmtflags
An implementation-defined integer, enumerated, or bitmask type that represents formatting flags for I/O [Constant values of this type are: boolalpha, dec, fixed, hex, internal, left, oct, right, scientific, showbase, showpoint, showpos, skipws, unitbuf, uppercase, adjustfield, basefield, floatfield]
iostate
An implementation-defined integer, enumerated, or bitmask type that represents the status (error state, if you like) of an I/O stream [Constant values of this type are: badbit, eofbit, failbit, goodbit = iostate(0)]
openmode
An implementation-defined integer, enumerated, or bitmask type that defines the mode for opening a file [Constant values of this type are: app, ate, binary, in, out, trunc]
seekdir
An implementation-defined enumerated type that specifies the origin for seeking (moving the "read pointer" or "write pointer") to a new file position [Constant values of this type are: beg, cur, end]
streamoff
An implementation-defined type that represents a signed offset in a stream [Values of type streammoff may be converted to values of type streamsize without losing information.]
streamsize
An implementation-defined signed integral type used to represent the size of various stream entities, such as the number of characters to read or write in an I/O operation [Values of type streamsize may be converted to values of type streamoff without losing information.]

The following is a list of parameterless manipulators available from this header.

left
Left-justify all output
right
Right-justify all output
internal
Left-justify sign or base indicator, and right-justify rest of number
dec
Display integers in base 10 (decimal) format
oct
Display integers in base 8 (octal) format
hex
Display integers in base 16 (hexadecimal) format
fixed
Use fixed point notation when displaying floating-point numbers (the usual convention)
scientific
Use exponential (i.e., scientific) notation when displaying floating-point numbers
showbase
noshowbase
Show (or don't show) base indicator when displaying integer output
showpoint
noshowpoint
Show (or don't show) decimal point when displaying floating-point numbers (default is 6 significant digits)
showpos
noshowpos
Show (or don't show) a leading plus sign (+) when displaying positive numbers
uppercase
nouppercase
Use (or don't use) uppercase E when displaying exponential numbers, and uppercase letters when displaying hexadecimal numbers
boolalpha
noboolalpha
Use (or don't use) textual rather than numerical format to read and write boolean values (i.e., use, or don't use, true and false rather than 1 and 0)
skipws
noskipws
Skip (or don't skip) whitespace on input
unitbuf
nounitbuf
Flush (or don't flush) output buffer after each insertion (which really has nothing to do with formatting)

stream.clear()
Clear all stream error flags

stream.good()
Return true if no error has occurred (i.e., the next three functions all return false)
stream.eof()
Return true if end-of-file has been encountered while attempting an input operation
stream.fail()
Return true if an input or output operation failed
stream.bad()
Return true if input or output error was so severe that recovery is unlikely

stream.flags()
Return a value of type fmtflags that contains the current values of all format-state flags
stream.flags(fmtflags_value)
Return a value of type fmtflags that contains the current values of all format-state flags, set all flags in fmtflags_value, and clear all flags not mentioned in fmtflags_value
stream.setf(fmtflags_value)
Set format-state flags specified in fmtflags_value, leave all other format-state flags unchanged, and return a value of type fmtflags that contains the previous state of all flags
stream.setf(fmtflags_value, fmtflags_group)
Set format-state flags specified in fmtflags_value as the new flags for the flag group identified by fmtflags_group, leave all other format-state flags unchanged, and return a value of type fmtflags that contains the previous state of all flags Typical uses of the two-parameter version of this function look like this:
stream.setf(ios::left, ios::adjustfield)
stream.setf(0, ios::floatfield)
That last version clears all flags in the ios::floatfield bit field.
stream.unsetf(fmtflags_value)
Clear format-state flags specified in fmtflags_value and leave all other format-state flags unchanged

stream.fill()
Return current fill character format-state parameter value as a value of type char
stream.fill(char_value)
Return current fill character format-state parameter value as a value of type char, and set fill character format-state parameter to new value in char_value
stream.precision()
Return current precision format-state parameter value as a value of type streamsize
stream.precision(streamsize_value)
Return current precision format-state parameter value as a value of type streamsize, and set precision format-state parameter to new value in streamsize_value
stream.width()
Return current fieldwidth format-state parameter value as a value of type streamsize
stream.width(streamsize_value)
Return current fieldwidth format-state parameter value as a value of type streamsize, and set fieldwidth format-state parameter to new value in streamsize_value

<iosfwd>

This header provides forward declarations of the various I/O-related classes and templates, but can be ignored by most programmers most of the time. In any case, this header is included by <ios>.


<iostream>

This header declares the following four "standard stream objects". They are all initialized and "set up for business" before the main program begins, and are not destroyed during normal program execution, so they can be used throughout the life of a program. You can tell from the class of each object which member functions are available for use with that object by checking the class type of the object and looking under the header containing that class heading elsewhere in this subsection of the current web page.


extern istream cin
The "standard input stream"
extern ostream cout
The "standard output stream"
extern ostream cerr
The "standard error stream"
extern ostream clog
The "standard log stream"

<istream>

This header declares the input stream classes and templates, and one input manipulator. In addition to the member functions given below, the extraction operator, operator>>, is of course overloaded to permit reading primitive values into variables, as well as the reading of characters into C-style string variables and C++ string objects.


istream inStream;
Declare an istream object that can be used for reading input
iostream ioStream;
Declare an istream object that can be used for reading input and/or writing output

ws
A manipulator that causes whitespace characters to be skipped

inStream.peek()
Return integer code of next character to be read without changing stream position (i.e., without actually reading the character and removing it from the stream), or return the integer code for end-of-file if there is no such character
inStream.ignore()
Ignore the next character in the stream, if there is one, and return *this
inStream.ignore(positive_integer_value)
Ignore positive_integer_value characters, or all characters up to the end-of-file, whichever comes first, and return *this
inStream.ignore(positive_integer_value, char_delimiter_value)
Ignore positive_integer_value characters, or all characters up to, and including, the character in character_delimiter_value, whichever comes first, and return *this [The most generally useful form of this function looks something like this: inStream.ignore(80, '\n'), which is often used to ignore everything on the rest of a line of input.]

inStream.get()
Read and return the integer code of the next single character from inStream, or return the integer code for end-of-file if there are no more characters to be read
inStream.get(char_variable)
Read the next single character from inStream into char_variable, and return *this
inStream.putback(char_value)
Try to put the character in char_value back into inStream so that it will be the next character read from the input stream, and return *this
inStream.unget(char_value)
Same as inStream.putback(char_value) (see immediately above)

In the following list, note that the difference between get() and getline() is simply that get() leaves the delimiter in the input stream, while getline() removes it. Also, a technical point that can cause some confusion if it actually occurs, and should thus be noted, is this: In the case of getline(), if the maximum number of characters to be read is exactly the same as the number of characters available before the delimiter, then the delimiter is not actually "encountered", and is therefore left in the input stream on such an occasion. The +1 in the n+1 parameter value can be thought of as an allowance for the extra space to accommodate the terminating null character ('\0') that the C-style string variable (into which the characters are being read) must contain.

inStream.get(c_string_variable, n+1)
Read up to n characters (or up to the newline character, whichever comes first) into c_string_variable
inStream.get(c_string_variable, n+1, char_delimiter_value)
Read up to n characters (or up to the first occurrence of char_delimiter_value, whichever comes first) into c_string_variable
inStream.getline(c_string_variable, n+1)
Read up to n characters (or up to the newline character, whichever comes first) into c_string_variable
inStream.getline(c_string_variable, n+1, char_delimiter_value)
Read up to n characters (or up to the first occurrence of char_delimiter_value, whichever comes first) into c_string_variable

inStream.read(c_string_variable, streamsize_value)
Read up to streamsize_value characters, place them in c_string_variable, and return *this [Note that no null character is appended to c_string_variable.]
inStream.gcount()
Return the number of characters returned from the stream by the most recent call to an unformatted member function (get(), getline(), ignore(), peek(), putback(), read() or unget())

inStream.tellg()
Return current position in an input stream as a value of type streamoff [The name tellg is short for "tell get", i.e., "tell" the position at which you may "get" a value.]
inStream.seekg(streamoff_value)
Move the "read pointer" in an input stream to the explicit position, or "offset" (measured by default from the beginning of the stream) specified by streamoff_value [The name seekg is short for "seek get", i.e., "seek a (new) position at which you may "get" a value.]
inStream.seekg(streamoff_value, seekdir_value)
Move the "read pointer" in an input stream in a direction determined by seekdir_value and a distance specified by streamoff_value

<ostream>

This header declares the output stream class templates, specializations and manipulators. See <fstream> for derived classes that write to files, <sstream> for derived classes that write to strings, and <ios> for base-class declarations. In addition to the member functions given below, the insertion operator, operator<<, is of course overloaded to permit output of primitive values, as well as C-style strings and C++ string objects.


ostream outStream;
Declare an ostream object that can be used for writing output

endl
Insert newline and flush the output stream
ends
Insert a null character
flush
Flush an output stream

outStream.flush()
Flush the output buffer and return *this

outStream.put(char_value)
Write the character in char_value to the stream and return *this

outStream.write(c_string_value, streamsize_value)
Write streamsize_value characters from c_string_value to the output stream and return *this

outStream.tellp()
Return current position in an output stream as a value of type streamoff [The name tellp is short for "tell put", i.e., "tell the position at which you may "put", or write, a value.]
outStream.seekp(streamoff_value)
Move the "write pointer" in an output stream to the explicit position, or "offset" (measured by default from the beginning of the stream) specified by streamoff_value [The name seekp is short for "seek put", i.e., "seek" a (new) position at which you may "put", or write, a value.]
outStream.seekp(streamoff_value, seekdir_value)
Move the "write pointer" in an output stream in a direction determined by seekdir_value and a distance specified by streamoff_value

<sstream>

This header declares classes, templates and other types for reading from and writing to string objects in memory in the same manner as reading from and writing to files.


The following declarations parallel the analogous declarations for file streams under <fstream>. In each case a string buffer is created in memory, which can then be used for input and/or output, as the case may be.

istringstream inStringStream;
Declare an istringstream object which is initially empty, but which can be used for input (after something is placed in it, of course)
istringstream inStringStream(string_variable);
Declare an istringstream object which has its buffer initialized with the contents of string_variable and which can be used for input
ostringstream outStringStream;
Declare an ostringstream object which is initially empty, but which can be used for output
ostringstream outStringStream(string_variable);
Declare an ostringstream object which has its buffer initialized with the contents of string_variable and which can be used for output
stringstream ioStringStream;
Declare a stringstream object which is initially empty, but which can be used for either input or output
stringstream ioStringStream(string_variable);
Declare a stringstream object which has its buffer initialized with the contents of string_variable and which can be used for either input or output

anyStringStream.str()
Return the contents of the string buffer associated with the stream as a string value
anyStringStream.str(string_variable)
Deallocate the current buffer and replace it with the contents of string_variable

<streambuf>

This header declares the basic_streambuf class template and its streambuf specialization, which provides a stream buffer object to manage low-level access to a sequence of characters. This header is not normally needed in day-to-day programming.


<strstream>

This header declares classes, templates and other types for reading from, and writing to, character arrays in memory, in the same manner as reading from and writing to files. This header and its classes are actually deprecated in the Standard, another hint that programmers should really be using C++ string objects and the facilities from <sstream> instead.