0% found this document useful (0 votes)
11 views

note2-CPP Programming Review

Uploaded by

tsuiii2010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

note2-CPP Programming Review

Uploaded by

tsuiii2010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

EE2331 Data Structures and

Algorithms
C++ Programming Review

1
Outline In the lecture, we won’t cover each page
but these are good reference for you.

n Standard Libraries
n Basic Data Types
n Arithmetic, Bitwise, Logical Operators
n Control Structures
n Pointers
n Arrays
n Composite Structures
n Parameter Passing in Functions
n Standard I/O
n Pseudo Code
n Suggestion for Good Programming Practice

2
Let us start from an example (1)
#include <cstdio> Header file

int main() program file


{
int A, B, C; //local variable declaration

printf("Enter the numbers A, B and C: "); //output function


scanf("%d %d %d", &A, &B, &C); //take inputs from standard input

if (A >= B && A >= C) //logic operator


printf("%d is the largest number.", A);

if (B >= A && B >= C)


printf("%d is the largest number.", B);

if (C >= A && C >= B)


printf("%d is the largest number.", C);

return 0; //return to OS (0=successful completion)


}

What is the purpose of this program?


3
C++ File Structure
Header file (.h) Program file (.cpp)

Functions declaration Functions implementation


Main program

A header file commonly contains forward declarations of subroutines.


Programmers who wish to declare functions in more than one source file
can place such declaration in a single header file, which other code can
then include whenever the header contents are required.

4
Example 2 (self-defined header file)

Can the above code compile


successfully? If not, how to fix?

5
Main Function
n There are two declarations of main that must be allowed:
n int main() // without arguments
n int main(int argc, char** argv) // with arguments
n The return type of main must be int.
n Return zero to indicate success and non-zero to indicate failure.
n You are not required to explicitly write a return statement in main(). If
you let main() return without an explicit return statement, it's the same
as if you had written return 0;.
n int main() { } // equivalent to the next line
n int main() { return 0; }
n There are two macros, EXIT_SUCCESS and EXIT_FAILURE, defined
in <cstdlib> that can also be returned from main() to indicate success
and failure, respectively.

6
Command Line Arguments
nC:\> assign1.exe dat1.txt data2 … xxx
Where’s the
location of
your Your compiled program 1st argument 2nd argument … nth
compiled
program? argv[0] argv[1] argv[2] … argv[n]

Total no. of arguments (i.e. argc = n + 1)

int main(int argc, char *argv[]) { argc: count

… argv: value

}
7
Example 3

A useful method to remind your


users of the input format!

After I compile this program, I got the executable program ex3.


Show the output of the following three commands:

Enter two integers

8
Command Line Arguments
int main(int argc, char *argv[]) {
printf(“argc = %d\n”, argc);
for (int i = 0; i < argc; i++)
printf("argv[%d] = %s\n", i, argv[i]);}

>ex1_2.exe 123 abc

argc = 3
argv[0] = ex1_2.exe //name of the program
argv[1] = 123 //string, not integer
argv[2] = abc

9
The Building Process
C Source Programs C Source Headers
(.cpp) (.h)

.o object Compilation
.a archive Compile time errors:
.obj object (MS) e.g. syntax errors
Object Files/Libraries
.lib library (MS)
(.o, .a, .obj, .lib)
.so shared object
.dll dynamic-link library (MS)
(Static) Linking

Shared Libraries Executable Programs Logical errors:


(.so, .dll) + (.exe) e.g. forever loop

Runtime errors:
Dynamic Linking e.g. stack overflow,
in Runtime null pointer exception,
10
array out of boundaries
Common Standard Library Header

n <cstdio>
n Standard I/O facilities: printf(), scanf(), getchar(),
fopen(), fclose(), etc
n <cstdlib>
n Standard utility functions: malloc(), free(), rand(), etc
n <cstring>
n String functions: strcpy(), strcmp(), memset(), etc
n <iostream>
n Perform both input and output operations with the
stream objects: cin and cout
11
Comments

/* Block comment 1 */

/*
* Block comment 2
*/

// Line comment

12
Primitive Data Types in C++
Data type Size Interpretation/representation Range of values
(byte)
bool 1 Boolean (not available in C) false or true
char 1 signed number (2’s complement) -128 to 127
unsigned char unsigned number 0 to 255
int signed number (2’s complement) -231 to 231-1
4
unsigned int unsigned number 0 to 232-1
short signed number (2’s complement) -215 to 215-1
2
unsigned short unsigned number 0 to 216-1
long signed number (2’s complement) -231 to 231-1
4
unsigned long unsigned number 0 to 232-1
long long signed number (2’s complement) -263 to 263-1
unsigned 8
unsigned number 0 to 264-1
long long
4 IEEE 32-bit floating point number ±1.4´10-45 to ±3.4´1038
float
8 IEEE 64-bit floating point number ±5´10-324 to
double ±1.798´10308
pointer 4 memory address 0 to 232-1

13
Operators in C++
Operator Symbol Description
Assignment =
Arithmetic +, -, *, /, %
Increment, ++, --
decrement
Unary minus -
Comparison ==, !=, <, <=, >, >=
Logical !, &&, ||
Bitwise ~, &, |, ^, <<, >>
insertion, cout << s insertion to an output stream
extraction cin >> i extraction from an input stream
Member and x[i] subscript (x is an array or a pointer)
pointer *x indirection, dereference (x is a pointer)
&x reference (address of x)
x->y structure dereference
(x is a pointer to object/struct; y is a member of the
object/struct pointed to by x)
x.y structure reference (x is an object or struct; y is a
member of x)

14
Use of Variables
n Declaration
n Given an identifier (variable name), you specify the
data type of it and hence implicitly reserve the
required memory space.
n Initialization
n Variables should be initialized before being used.

int a;
cout << a; // prints dummy value

15
Arithmetic Operators
nAddition
int a, b, c;
a = 1;
b = 2;
c = a + b;
printf(“%d\n”, c);

nMind the overflow problem


int a, b, c;
a = b = 2147483647; //the largest value of signed int
c = a + b;
printf(“%d\n”, c); 16
Arithmetic Operators
nSubtraction
int a, b, c;
a = 1;
b = 2;
c = a - b;
printf(“%d\n”, c);

nMind the underflow problem


int a, b, c;
a = -2147483648; //the smallest value of signed int
b = 2147483647; //the largest value of signed int
c = a – b;
17
printf(“%d\n”, c);
Arithmetic Operators
nDivision
int a, b, c;
a = 5;
b = 2;
c = a / b;
printf(“%d\n”, c); // output is 2

nInteger truncation occurs

18
Arithmetic Operators
nRemainder (Modulus Operator)
int a, b, c;
a = 5;
b = 2;
c = a % b;
printf(“%d\n”, c);

nWhen to use it?


nGenerate periodic values
nTo wrap around the array index (in Queue)
nTo determine the hash key (in Hash table)
19
Bitwise & Logical Operators
nBitwise OR
int a, b, c; a 00000101
a = 5;
OR
b = 3;
c = a | b; b 00000011
printf(“%d\n”, c);

=
nLogical OR c 00000111
int a, b, c;
a = 5;
b = 3;
c = a || b;
printf(“%d\n”, c);
20
Bitwise & Logical Operators
nBitwise AND
int a, b, c; a 00000101
a = 5;
AND
b = 3;
c = a & b; b 00000011
printf(“%d\n”, c);

=
nLogical AND c 00000001
int a, b, c;
a = 5;
b = 3;
c = a && b;
printf(“%d\n”, c);
21
Bitwise Operators
nExclusive OR
int a, b, c; a 00000101
a = 5;
b = 3; XOR
c = a ^ b; b 00000011
printf(“%d\n”, c);

=
nWhen to use it? c 00000110

nInterchange two variables (in Bubble Sort)

22
Bitwise Operators
nLeft Shift (x2)
int a, b; a 00000101
a = 5;
b = a << 1;
printf(“%d\n”, b); b 00001010

nRight Shift (/2)


int a, b;
a = 5;
b = a >> 1;
printf(“%d\n”, b); b 00000010

23
Variable Assignments
nExample 1
int a, b, c;
a = b = c = 5;
printf(“%d\n”, a);

nExample 2
int a = 5, b = 5, c = 5;
a = b == c;
printf(“%d\n”, a);

What are the outputs of the two examples?


24
Typecasting
nExample 1 - Implicit
int a;
float b = 10.5;
a = b; // precision loss with warning
printf(“%d %f\n”, a, b); // 10 10.5

nExample 2 - Explicit
int a;
float b = 10.5;
a = (int) b; // still precision loss but NO warning
printf(“%d %f\n”, a, b); // 10 10.5

25
Typecasting
nExample 3
int a = 3;
int b = 2;
int c = 4;
cout << a / b * c << endl; // output is 4 !!
cout << a * c / b << endl; // output is 6

n The resultant type of an arithmetic operation will be


promoted to the type of the operators with larger
precision.
n int / int à int
n float / int à float
26
Control Structures

27
If-then-else
n? : (ternary operator)
nequivalent to if-then-else
nexpression ? true instruction : false instruction;
if (a < b)
min = a;
else
min = b;

min = a < b ? a : b;

28
For-Loop and While-Loop
n for-loop and while-loop are interchangeable

for (initialization; loop_test; loop_counting) {


//loop-body
}

initialization;
while (loop_test) {
//loop-body
loop_counting;
}

29
Jump Statements
n Jump statements allow the early termination of loops

n These cause unconditional branches


n goto is bad practice and will not be dealt with
n break will exit the inner most loop
n continue will force the next iteration
n return will return to the calling function
n exit will quit the program

30
Breaking Out Loops Early

for (i = 0; i < n; i++) {



if (…) break; //to break out the for-loop

}

while (…) {

if (…) continue; //to skip the rest part of current iteration,
//and continue for next iteration

}
31
Bad Styles of Loop
// DON’T use != (Not equal) to test the end of a range
for (i = 1; i != n; i++) {
//loop body
}
// How does the loop behave if n happens to be zero or negative?

// DON’T modify the value of the loop-counter inside the loop body of a for-loop.
for (i = 1; i <= n; i++) {
//main body of the loop
if (testCondition)
i = i + displacement;

//i++ is executed before going back to top of the loop


}
32
Breaking Out Functions Early
void func(…) {

if (…) return; //to break out the function

}

int func(…) {

if (…) return 0; //to break out the function, and
//return a value to the calling function

}
33
Breaking Out Programs Early
void func(…) {

if (…) exit(0); //to terminate the program, and
//return normal exit value 0 to operating
… //system!
}

int main(…) {

if (…) exit(1); //to terminate the program, and
//return abnormal exit value 1 to
… //operating system!
return 0; //normal completion of the program
34
}
Loop Design
n Find the maximum value in an array of integers.
n Any mistake in this program?

int max(int a[], int n) { //n = no. of elements in a[]


int m = 0; // variable to store the max value
for (int i = 0; i < n; i++)
if (a[i] > m)
m = a[i];
return m;
}

35
Pointers and Arrays

36
Note: The actual size of integers and
Pointers pointers are 4-byte long

1 int a, *p; ????? ?????


1 ??? ???
2 a = 5;
a p
3 p = &a; 0xFF00 0xFF04

00101 ?????
a: value of a (i.e. 5)
2 000 ???
&a: address of a (i.e. 0xFF00)
*a: ? a 0xFF00 p 0xFF04

p: value of p == address of a (i.e. 0xFF00) 01


1 00
&p: address of p (i.e. 0xFF04) 00000 0xFF
3
*p: value pointed by p (i.e. 5)
a 0xFF00 p 0xFF04
37
Pointers Example
int x = 1, y = 2;
int *a, *b, *c;

a = &x;
b = &y;
printf(“%d %d %d %d\n”, x, y, *a, *b); 1 2 1 2

c = a; // swap a with b
a = b;
b = c;
printf(“%d %d %d %d\n”, x, y, *a, *b); 1 2 2 1

38
Creation of Array
1
1 int a[5];
????? ????? ????? ????? ?????
a[0] = 5; ??? ??? ??? ??? ???
a[1] = 8;
a[2] = 3; a 0xFF00 0xFF04 0xFF08 0xFF0C 0xFF10

a[3] = 6;
2 a[4] = 9; 2

00101 01000 00011 00110 01001


000 000 000 000 000

a 0xFF00 0xFF04 0xFF08 0xFF0C 0xFF10

Note: the elements of integer array should be 4-byte long.


39
Base Address of Arrays
Initialization, set size implicitly

1 int a[] = {5, 8, 3, 6, 9}; The array variable ‘a’ is


interpreted as a pointer pointing
int *p;
to the first element (base
2 p = a; //why not p = &a; ?? address) of the array.

1 00101 01000 00011 00110 01001


000 000 000 000 000

a 0xFF00 0xFF04 0xFF08 0xFF0C 0xFF10

base address 2 x F F 00 a[0]: the value of the 1st element (= 5)


0
? ???? a: the address of the 1st element (= 0xFF00)
??? p: the value of p (= 0xFF00)
&p: the address of p (= 0xFF14)
p &a: ? 40
0xFF14
C-String (Character Array)
1 char a[] = “Hello”;
char *p;
2 p = a;
Null character (‘\0’) filled at the end
printf(“%d\n”, sizeof(a)); of character array (string)

1 H e l l o \0

a 0xFF00 0xFF01 0xFF02 0xFF03 0xFF04 0xFF05

2 x F F 00 Note: the actual representation


0 of char is ASCII code.
? ????
???

p 41
0xFF06
2D Arrays
Multi-dimensional arrays are mapped to
int a[2][3]; //2 rows, 3 columns the linear address space of the
computer system.

???? ???? ???? ???? ???? ?????


???? ???? ???? ???? ???? ???

a 0xFF00 0xFF04 0xFF08 0xFF0C 0xFF10 0xFF14


a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]

a[0][0] a[0][1] a[0][2]

????? ????? ????? In C/C++, elements of a multi-


a ????? ????? ?????
?? ?? ?? dimensional array are arranged
???? ???? ???? in row-major order.
0xFF01 0xFF01 0xFF02
0xFF0C 0xFF10 0xFF14 42
a[1][0] a[1][1] a[1][2]
Size of Array
n The size of array is fixed and predetermined
n Cannot declare an array with variable size
#define n 10 //n is a macro
int i, a[n]; //ok, n is substituted by 10 during compilation
for (i = 0; i < n; i++)
a[i] = i;

int n=100; // n is a variable


int i, a[n]; // compilation error
for (i = 0; i < n; i++)
a[i] = i;
43
Boundaries of Array
n C/C++ will not check the boundaries of array
int a[10];
a[11] = 0; //allow to run (dangerous!)
//but result is unpredictable!

n It is the responsibility of programmers to ensure


not going out the boundaries
int a[10];
int i = 11;
if (i >= 0 && i < 10) a[i] = …; //boundaries checking
44
Composite Structures

45
Typedef
nTo rename a type to a new name
typedef int NUM;
int func(int x) { NUM func(NUM x) {
return x*x; return x*x;
} equivalent }
int main(…) { int main(…) {
int a, b; NUM a, b;
a = 1; a = 1;
b = func(a); b = func(a);
… …
} }

46
Structures
nTo define a composite structure
struct name{
data_type1 member1;
data_type2 member2;

};

nTo refer to this structure, use


struct name // C
name // C++

47
Structure weight price

6 4.0
1
struct Product{ orange 0xFF00
int weight;
float price; 5 3.5
2
}; apple
0xFF08

int main(…) {
1 Product orange = {6, 4.0}; A structure can be initialized by
Product apple; using {}
apple.weight = 5; Or use the . (dot) operator to
2 apple.price = 3.5; access the member of a
printf(“%d\n”, apple.weight); structure

} 48
Pointer to Structure weight price

6 4.0
1
struct Product{ orange 0xFF00
int weight; 0xFF00 3
float price;
2 ????
}; p
0xFF08

int main(…) {
1 Product orange = {6, 4.0};
2 Product *p; Use the arrow -> operator to
3 p = &orange; access the member of pointer-
printf(“%d\n”, p->weight); to-structure
printf(“%d\n”, (*p).weight);

} 49
Parameter Passing in
Functions

50
Parameter Passing in Functions
n Pass by value
n Involve copying the value of parameters
n Pass by pointer
n Just pass the address of the parameters, without copying the
value of them
n Usually used in passing large-size data structures, e.g. arrays,
structures, objects, lists, etc
n Pass by reference
n C++ reference is similar to pass-by-pointer but without the
hassles of pointers’ (&)reference/ (*)dereference syntax
n You can specify a formal parameter in the function signature as
a reference parameter

51
Pass by Value
void plus_one(int x, int y) {
x++; y++;
}

int a = 5, b = 3;
plus_one(a, b);

6 4
5 3 5 3

a 0xFF01 b 0xFF04 x 0xAA01 y 0xAA04


The values of a, b have not been A new set of variables is duplicated
52
modified in function plus_one
Pass by Pointer
void plus_one(int *x, int *y) {
(*x)++; (*y)++; pointers
}

int a = 5, b = 3; addresses

plus_one(&a, &b);

6 4
01 04
5 3 0xFF 0xFF

a 0xFF01 b 0xFF04 x 0xAA01 y 0xAA04


The values of a, b have been The new set of variables is actually53
modified! pointing to a, b
Pass by Reference
void plus_one(int &x, int &y) {
x++; y++; reference parameters
}

int a = 5, b = 3;
plus_one(a, b);

6 4
01 04
5 3 0xFF 0xFF

a 0xFF01 b 0xFF04 x 0xAA01 y 0xAA04


The values of a, b have been The new set of variables is actually54
modified! referencing to a, b
C++ Reference Example
int i = 2;
//an initial value must be provided in the declaration of r
int &r = i; //r is a reference to an integer
int *p = &i; //p is a pointer to an integer

printf(“%d %d %d %d\n”, i, r, p, *p);


// output: 2 2 001AF9C0 2

r = 4;
printf(“%d %d\n”, i, r);
// output: 4 4

55
Reference vs. Pointer
1. Pointers can point nowhere (NULL), whereas reference always
refers to an object.
2. References must be initialized as soon as they are created.
3. A pointer can be re-assigned any number of times while a
reference cannot be re-seated after binding.
4. You cannot take the address of a reference like what you can do
with pointers. Any occurrence of its name refers directly to the
object it references.
5. There is no reference arithmetic but you can take the address of an
object pointed by a reference and do pointer arithmetic on it
(because of #4).

56
Pseudo Code
n We need a language to express program development
n English is too verbose and imprecise.
n The target language, e.g. C/C++, requires too much details.
n Pseudo code resembles the target language in that
n it is a sequence of steps (each step is precise and unambiguous)
n it has similar control structure of C/C++
n Pseudo code is a kind of structured English for describing algorithms. It allows the
designer to focus on the logic of the algorithm without being distracted by details of
language syntax.

x = max{a, b, c} x = a;
if (b > x) x = b;
if (c > x) x = c;

Pseudo code C++ code


57
Pseudo Code Example
n An m´n matrix is said to have a saddle point if some entry A[i][j] is
the smallest value on row i and the largest value in column j.

An 6´8 matrix with a saddle point


11 33 55 16 77 99 10 40
29 87 65 20 45 60 90 76
50 53 78 44 60 88 77 81
46 72 71 23 88 26 15 21
65 83 23 36 49 57 32 14
70 22 34 19 54 37 26 93

n Problem:
n Given an m×n matrix, determine if there exists one or more saddle
points.

58
Pseudo Code Solutions
// high-level pseudo code solution
for each row {
j = index of the smallest element on row i;
if (A[i][j]) is the largest element in column j)
A[i][j] is a saddle point;
}

// refined pseudo code


for (i = 0; i < m; i++) { //for each row
j = index of the smallest element on row i;
for (k = 0; k < m; k++) //for each element in column j
if there does not exist A[k][j] > A[i][j]
A[i][j] is a saddle point;
}

59
Suggestions for Good Style
n Use informative and meaningful variable names
n Insert useful comments (i.e. assertions) in the source program
n Format the source file with proper indentation of statements and align the braces so
that the control structures can be read easily
n Do not use goto statement, especially backward jump
n Use single-entry single-exit control blocks, or at most one break statement inside a
loop
n Avoid ambiguous statements e.g. x[i] = i++;
n Minimize direct accesses to global variables, especially you should avoid modifying
the values of global variables in a function
n Always make a planning of the program organization and data structures before start
writing program codes
n Should avoid using the trial-and-error approach without proper understanding of the
problem to be solved
n Avoid side effects (see example in next page)

60
Standard Input / Output

61
cin & cout
n Default input/output stream objects
n A stream is a sequence of bytes (characters)
that can be read from or written to
n cin is a stream on the keyboard input
n cout is a stream on the screen output

n The extractor (>>) / insertor (<<) is used to


read/write from/to the input/output stream
Standard Output
#include <cstdio> How to output the values to
standard output (screen)?
#include <iostream>
using namespace std; Use printf() in <cstdio>:
n integer: %d
… float: %f
int x = 1; character: %c
string: %s
float y = 2.5;
Use cout in <iostream>:
char z = ‘a’;
n cout is defined in the std
char w[80] = “xxxxxx”; namespace
n Use insertion operator to insert
values to output stream.
printf("%d %f %c %s\n", x, y, z, w);
n Multiple insertions can be chained.
std::cout << x; n Use endl to set a new line.
cout << endl;
cout << y << " " << z << " " << w;
63
Standard Input
#include <cstdio> How to read the values from
#include <iostream> standard input (console)?
using namespace std; Use scanf() in <cstdio>:
… n integer: %d
float: %f
int x; character: %c
string: %s
float y;
Use cin in <iostream>:
char z;
n cin is defined in the std
char w[80]; namespace
n Use extraction operator to
extract values from input
cin >> x; stream.
scanf(“%f”, &y);
cin >> z;
scanf(“%s”, w);
64
scanf()
n scanf can only read a “word”, but not a sentence. It stops reading if
meets whitespace characters.
n What are whitespace characters?
n Blank space: ‘ ’
n Newline: ‘\r’ ‘\n’
n Tab: ‘\t’
n Visual Studio compiler will tell you the function scanf is not safe.
n Add this code to the beginning of your program to suppress this MS
secure warning

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

65
scanf() Examples
scanf() will stop reading when it meets enter, space or tab (whitespace)

scanf(“%s”, w); abc<enter>


printf(“##%s##\n”, w); ##abc##

The newline character has been ignored by scanf()

Space

scanf(“%s”, w); abc def<enter>


printf(“##%s##\n”, w); ##abc##

The space and following characters have been ignored by scanf()

66
More on Input
n When looking for the input value in the stream, the >> operator skips any
leading whitespace characters and stops reading at the first character that
is inappropriate for the data type (whitespace or otherwise).
n You can use the get() function to input the very next character in the input
stream without skipping any whitespace characters:
char someChar;
cin.get(someChar);
n The ignore() function is used to skip characters in the input stream:
cin.ignore(200, ‘\n’);
n The first parameter is an int expression; the second, a char value. This
skips the next 200 characters or until a newline character is read, whichever
comes first
Output Manipulators
n Manipulators change the output format of your data. To use them, you will
need to include this header in your C++ source code.
#include <iomanip>
n setw() sets the width of the field to be printed to the screen
n cout << 5 << setw(4) << 6 << 7; // output:5 67
n setprecision() sets the decimal precision to be used to format floating-point
values:
n cout << setprecision(5) << 3.14159; // 3.1416
n cout << setprecision(1) << 3.14159; // 3
n To specify the number of digits after the decimal point:
n cout << setiosflags(ios::fixed); // not use scientific notation
n cout << setprecision(2) << 12.1234; // 12.12
n Other floating point output flags:
n setiosflags(ios::scientific); // use scientific notation
n resetiosflags(ios::floatfield) // restores default (use fixed
// or scientific notation based
// on the precision)
File Input/Output
n In a similar way C++ provides streams which can manipulate files
n C++ provides 2 file streams
ifstream input file stream
ofstream output file stream
Must #include <fstream> to use them

n Example:
#include <fstream>

int number;
ifstream in("in.dat");
ofstream out("out.dat");
in >> number;
out << number;
Input File Streams (ifstream)
n Allows data to be read from a file
n An input file stream can be defined as follows:
ifstream stream_var(filename);
Example:
ifstream inFile("test.dat");

n If stream opened successfully, inFile evaluates to positive and the


stream becomes attached to the file test.data
n If stream open failed (e.g. file does not exist) inFile evaluates to zero

n Important: Effects of reading data from file which has failed to open
is undefined
Input File Streams (ifstream)
n When file opened successfully, data can be read using normal
extractor functions
int n;
char c;
ifstream inFile("test.dat");
inFile >> n;
inFile.get(c);
inFile.ignore(100, 'A');
inFile.close();

n Note: When a file stream goes out of scope it will automatically


close the file it is attached to
File Input Failure/End
n To check if the file has been opened or not, you can use:
if (inFile) // testing if the file opened successfully
{ ... }
n To test for end of file, you can use:
while (!inFile.eof())
{ ... }
For instance:
int number;
inFile >> number; // reading number from a file
while (!inFile.eof())
{
cout << number; // print number on screen
inFile >> number;
}
Output File Stream (ofstream)
n Allows data to be written to a file
An output file stream can be defined as follows:
ofstream stream_var(filename);
Example:
ofstream outFile("temp.data");
n If stream opened successfully, outFile evaluates to positive and the
stream becomes attached to the file temp.data
n If stream open failed (e.g. no disk space) outFile evaluates to zero

n Note:
n If the file already exists its contents will be deleted
n If the file does not exist, a file with the same name is created
n Data can be appended to a file by using constructor with two arguments
ofstream outFile("temp.data", ios::app);
Example on How to Write to a File

#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main ()
{
float first, second, sum; // Declaring variables
ofstream outFile("out.dat"); // Opening file for output
cout << "Enter two numbers" << endl;
cin >> first >> second; // Reading in the two numbers
sum = first + second;
outFile << setiosflags(ios::fixed); // Formatting the output
outFile << setprecision(2);
outFile << sum << endl; // Writing into the file
return 0;
}

You might also like