P. 1
C and C++ in 5 days

C and C++ in 5 days

|Views: 184|Likes:
Published by xinuxnet
learn C and C++ in five days
learn C and C++ in five days

More info:

Published by: xinuxnet on Jan 19, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

12/14/2012

pdf

text

original

One additional point is worth explaining now: input and output using the iostream
library. It defines three widely used standard streams: cout, cin and cerr, based on the
UNIX convention of standard out, standard in and standard error. Output to a stream is
strung together with the << operator, while input is strung together with >> (also used—as
in C—respectively, as left and right shift bit operators).
Use of the default streams (C++ has end-of-line comments, started by //):
#include
void main ()
{

cout << "Enter a number : ";

// no line break

cin >> i;
cerr << "Number out of range" << endl;// endl ends line

}

/* can also use C-style comment */

if you need to use files, use

#include

A stream can be associated with a file for output (ios::out is an enum value):
ofstream my_out ("file.txt", ios::out);

and used to write to the file:

my_out << "A line of text ended by a number : " << 100 << endl;

To read the file:

ifstream my_in ("file.txt", ios::in);
char data[100];
my_in >> data;

You can also explicitly open the file, if you didn’t connect the ifstream or ofstream
object to a file when you defined it:

#include

/* for exit () */

ifstream my_in;
my_in.open ("file.txt", ios::in);
if (!my_in)
{

cerr << "open failed" << endl;
exit (-1);

// kill program returning error code

}
// use the file ... then finally:
my_in.close ();

If you need to do both input and output on a file, declare it as class fstream; open
with ios::in|ios::out which combines the two modes using a bitwise or.

caution: I/O is one of the most system-dependent features of any
language. Streams should work on any C++ but file names are system-
specific (.e.g., DOS’s “\” path separator, vs. UNIX’s “/”)

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->