03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

2.7. INPUT AND OUTPUT 45<br />

std::ifstream datafile( ”file.dat” ) ;<br />

assert( datafile.is open() );<br />

datafile.close();<br />

return 0;<br />

}<br />

In this example, assert is used to abort the program execution if datafile compares equal to 0,<br />

which happens when the opening of the file was unsuccessful.<br />

2.7 Input and output<br />

C ++ uses a convenient abstraction called streams to per<strong>for</strong>m input and output operations in<br />

sequential media such as the screen or the keyboard. A stream is an object where a program<br />

can either insert characters to or extract from. The standard C ++ library includes the header<br />

file iostream, where the standard input and output stream objects are declared.<br />

2.7.1 Standard Output (cout)<br />

By default, the standard output of a program is the screen, and the C ++ stream object defined<br />

to access it, is cout.<br />

cout is used in conjunction with the insertion operator, which is written as ≪ . It may be used<br />

more than once in a single statement. This is especially useful if we want to print a combination<br />

of variables and constants or more than one variable. Consider this example:<br />

std::cout ≪ ”Hello World, my name is ” ≪ name ≪ std::endl ;<br />

std::cout ≪ ”I am ” ≪ age ≪ ” years old.” ≪ std::endl ;<br />

If we assume the name variable to contain the value Jane and the age variable to contain 25<br />

the output of the previous statement would be:<br />

Hello World, my name is Jane.<br />

I am 25 years old.<br />

The endl manipulator produces a newline character. An alternative representation of endl is the<br />

character ’n’.<br />

2.7.2 Standard Input (cin)<br />

The standard input device is usually the keyboard. Handling the standard input in C ++ is done<br />

by applying the overloaded operator of extraction ≫ on the cin stream. The operator must be<br />

followed by the variable that will store the data that is going to be extracted from the stream.<br />

For example:<br />

int age;<br />

std::cin ≫age;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!