Search This Blog

Wednesday, July 28, 2010

iostream

iostream is a header file which is used for input/output in the C++ programming language. It is part of the C++ standard library. The name stands for Input/OutputStream. In C++ and its predecessor, the C programming language, there is no special syntax for streaming data input or output. Instead, these are combined as alibrary of functions. Like the cstdio header inherited from C's stdio.hiostream provides basic input and output services for C++ programs. iostream uses theobjects cincoutcerr, and clog for sending data to and from the standard streams input, output, error (unbuffered), and error (buffered) respectively. As part of the C++ standard library, these objects are a part of the std namespace.



Example usage

The canonical Hello world program can be expressed as follows:
#include 
using namespace std;
 
int main()
{
    cout << "Hello, world!\n";
    return 0;
}
This program would output "Hello, world!" followed by a newline.
The cout object is of type ostream, which overloads the left bit-shift operator to make it perform an operation completely unrelated to bitwise operations. The cerrand clog objects are also of type ostream, so they overload that operator as well. The cin object is of type istream, which overloads the right bit-shift operator. The directions of the bit-shift operators make it seem as though data is flowing towards the output stream or flowing away from the input stream.
An alternative to the newline character \n is endl, which is used as follows:
#include 
using namespace std;
 
int main()
{
    cout << "Hello, world!" << endl;
    return 0;
}
endl is an output manipulator that writes a newline and flushes the buffer, ensuring that the data is output immediately. Several other manipulators are listed below.


Output formatting

Methods

width(int x)minimum number of characters for next output
fill(char x)character used to fill with in the case that the width needs to be elongated to fill the minimum.
precision(int x)sets the number of significant digits for floating-point numbers
Example:
cout.width(10);
cout << "ten" << "four" << "four";


Manipulators

Manipulators are objects that can modify a stream using the << or >> operators.
endl"end line": inserts a newline into the stream and calls flush.
ends"end string": inserts a null character into the stream and calls flush.
flushforces an output stream to write any buffered characters
decchanges the output format of number to be in decimal format
octchanges the output format of number to be in octal format
hexchanges the output format of number to be in hexadecimal format
wscauses an inputstream to 'eat' whitespace
showpointtells the stream to show the decimal point and some zeros with whole numbers
Other manipulators can be found using the header iomanip.

math.h


math.h is a header file in the standard library of the C programming language designed for basic mathematical operations. Most of the functions involve the use of floating point numbers. C++ also implements these functions for compatibility reasons and declares them in the header cmath.
All functions that take or return an angle work in radians.
All these functions take doubles for floating-point arguments, unless otherwise specified. To work with floats or long doubles, append an f or an l to the name, respectively.

Classes

In C++, a class is declared using the class keyword. The syntax of a class declaration is similar to that of a structure. Its general form is,
class class-name {
// private functions and variables
public:
// public functions and variables
} object-list;
In a class declaration the object-list is optional.
The class-name is technically optional. From a practical point of view it is virtually always needed. The reason is that the class-name becomes a new type name that is used to declare objects of the class.
Functions and variables declared inside the class declaration are said to be members of the class.
By default, all member functions and variables are private to that class. This means that they are accessible by other members of that class.
To declare public class members, the public keyword is used, followed by a colon. All functions and variables declared after the public specifier are accessible both by other members of the class and by any part of the program that contains the class.
#include < iostream >
using namespace std;
// class declaration
class myclass {
// private members to myclass
int a;
public:
// public members to myclass
void set_a(int num);
int get_a( );
};
This class has one private variable, called a, and two public functions set_a( ) and get_a( ). Notice that the functions are declared within a class using their prototype forms. The functions that are declared to be part of a class are called member functions.

Since a is private it is not accessible by any code outside myclass. However since set_a( ) and get_a( ) are member of myclass, they have access to a and as they are declared as public member of myclass, they can be called by any part of the program that contains myclass.
The member functions need to be defined. You do this by preceding the function name with the class name followed by two colons (:: are called scope resolution operator). For example, after the class declaration, you can declare the member function as
// member functions declaration
void myclass::set_a(int num) {
a=num;
}
int myclass::get_a( ) {
return a;
}
In general to declare a member function, you use this form:
return-type class-name::func-name(parameter- list)
{
// body of function
}
Here the class-name is the name of the class to which the function belongs.
The declaration of a class does not define any objects of the type myclass. It only defines the type of object that will be created when one is actually declared. To create an object, use the class name as type specifier. For example,
// from previous examples
void main( ) {
myclass ob1, ob2;//these are object of type myclass
// ... program code
}
Remember that an object declaration creates a physical entity of that type. That is, an object occupies memory space, but a type definition does not.
Once an object of a class has been created, your program can reference its public members by using the dot operator in much the same way that structure members are accessed. Assuming the preceding object declaration, here some examples,

ob1.set_a(10); // set ob1’s version of a to 10
ob2.set_a(99); // set ob2’s version of a to 99
cout << ob1.get_a( ); << "\n";
cout << ob2.get_a( ); << "\n";
ob1.a=20; // error cannot access private member
ob2.a=80; // by non-member functions.
...
There can be public variables, for example
#include < iostream >
using namespace std;
// class declaration
class myclass {
public:
int a; //a is now public
// and there is no need for set_a( ), get_a( )
};
int main( ) {
myclass ob1, ob2;
// here a is accessed directly
ob1.a = 10;
ob2.a = 99;
cout << ob1.a << "\n";
cout << ob1.a << "\n";
return 0;
}
It is important to remember that although all objects of a class share their functions, each object creates and maintains its own data.

C AND C++ COMMENTS

/*
This is a C-like comment.
The program determines whether
an integer is odd or even.
*/
#include < iostream >
using namespace std;
int main( ) {
int num; // This is a C++ single-line comment.
// read the number
cout << "Enter number to be tested: ";
cin >> num;
// see if even or odd
if ((num%2)==0) cout << "Number is even\n";
else cout << "Number is odd\n";
return 0;
}
Multiline comments cannot be nested but a single-line comment can be nested within a multiline comment.
/* This is a multiline comment
Inside which // is nested a single-line comment.
Here is the end of the multiline comment.
*/

Preprocessing directives


A C++ program consists of several types of preprocessing directives and statements. Preprocessing
directives are interpreted before compilation, must be limited to one line of text, are all prepended by
a hash character ‘#’ and do not necessarily terminate with a semicolon character ‘;’. The purpose of
preprocessing directives is mostly to enable conditional compilation and include other source files in the
current compilation. Some examples:
#define MYCONSTANT 10
#include
#include "myheader.h"
#ifdef DEBUG
const char version[] = "Debug";
#else
const char version[] = "Release";
#endif
The first line defines a constant called MYCONSTANT to take the value 10. Each time the string “MYCONSTANT”
appears in the rest of the program being compiled, it will be replaced by the string “10”.
The purpose of isolating constants to the beginning of the source file, where all the #defines are usually
kept, is to avoid having to hunt for constants within the whole file each time the constant is changed.
Although #defines are very popular in the C language, in C++ one usually uses equivalent constructs
which are not preprocessing directives, such as
const int MYCONSTANT = 10;
which is a normal C++ statement. The second line instructs the compiler to look for a file called iostream
within the compiler’s include search path (i.e. a predetermined list of paths within the filesystem where
a lot of include files are stored; typically, on Unix systems, this is /usr/include:/usr/local/include),
read it, and compile it as if it was part of the source code being compiled. The third line is similar to
the second but the slightly different syntax indicates that the file myheader.h is a user-created file and
probably resides in the current directory. Lines 4-8 are a conditional preprocessing directive, instructing
the compiler to define the character array version differently according as to whether the preprocessing
symbol DEBUG was defined or not when the compiler was called. It is possible to define such symbols
either explicitly, by including a preprocessor directive #define DEBUG before the conditional statement,
or implicitly by launching the compiler from the shell with the -DDEBUG option.

History



Bjarne Stroustrup, creator of C++
Bjarne Stroustrup began work on "C with Classes" in 1979. The idea of creating a new language originated from Stroustrup's experience in programming for his Ph.D. thesis. Stroustrup found that Simula had features that were very helpful for large software development, but the language was too slow for practical use, while BCPL was fast but too low-level to be suitable for large software development. When Stroustrup started working in AT&T Bell Labs, he had the problem of analyzing the UNIX kernel with respect to distributed computing. Remembering his Ph.D. experience, Stroustrup set out to enhance the Clanguage with Simula-like features. C was chosen because it was general-purpose, fast, portable and widely used. Besides C and Simula, some other languages that inspired him were ALGOL 68AdaCLU and ML. At first, the class, derived class, strong type checking, inlining, and default argument features were added to C via Stroustrup's C++ to C compiler, Cfront. The first commercial implementation of C++ was released in October 1985.
In 1983, the name of the language was changed from C with Classes to C++ (++ being the increment operator in C). New features were added includingvirtual functions, function name and operator overloading, references, constants, user-controlled free-store memory control, improved type checking, and BCPL style single-line comments with two forward slashes (//). In 1985, the first edition of The C++ Programming Language was released, providing an important reference to the language, since there was not yet an official standard. Release 2.0 of C++ came in 1989.[citation needed] New features included multiple inheritance, abstract classes, static member functions, const member functions, and protected members. In 1990, The Annotated C++ Reference Manual was published. This work became the basis for the future standard. Late addition of features included templatesexceptionsnamespaces, new casts, and a Boolean type.
As the C++ language evolved, the standard library evolved with it. The first addition to the C++ standard library was the stream I/O library which provided facilities to replace the traditional C functions such as printf and scanf. Later, among the most significant additions to the standard library, was the Standard Template Library.