Advanced C/C++ Programming Guide
Advanced C/C++ Programming Guide
Published on
November 2021
Authors
Reviewers
Graphics
The European Commission support for the production of this publication does not
constitute an endorsement of the contents which reflects the views only of the authors,
and the Commission cannot be held responsible for any use which may be made of
the information contained therein.
All trademarks and brand names mentioned in this publication and all trademarks and
brand names mentioned that may be the intellectual property of third parties are
unconditionally subject to the provisions contained within the relevant law governing
trademarks and other related signs. The mere mention of a trademark or brand name
does not imply that such a trademark or brand name is not protected by the rights of
third parties.
ISBN 978-80-558-1780-4
Table of Contents
In C++, objects called streams are used to control files. A stream object contains a
number of operations that can be performed on files. There are files of different
types and are used in different modes, which is done by different stream variants.
Using the I/O Stream library, we can open the file by connecting it to the input,
output or input/output stream. In order to do this, we should attach a library:
All functions needed to access files are declared by these classes. To define the
object of the required type of stream we use, for example:
If the file does not exist then it will be created. We can close the file explicitly by
using
file.close();
📝 1.1.2
In order to both read and write from/to file, you must attach the _____.
• fstream library
• ofstream library
• ifstream library
6
Files – Text Files | FITPED
📝 1.1.3
• ifstream f1;
• ofstream f1;
• ifstream f1("file_name");
• fstream f1;
📝 1.1.4
fstream f2;
• False
• True
📝 1.1.5
In order to check whether the file was successfully opened, we can use a
conditional statement if(stream_name). Any stream can be assigned to a bool
object. The object will be true if the stream is in the correct state; otherwise it will
be false.
Alternatively, we can use the stream check function: good() or is_open(). Both
functions return true if the file has been accessed. We use them as follows
stream_name.good() or stream_name.is_open()
7
Files – Text Files | FITPED
There is also eof() function that returns true if a file open for reading has reached
the end.
🕮 1.2.2
First of all, we can read data from a file in analogy to stream cin>>
Data that has been read in this way is always treated as text. By using this method,
we will not read any information about whitespace (enter, tab, space, etc.).
We can also read data from a file using the function get(). Example
Another way to read data from a file is to use the function getline().
An example of using the getline() function from the <string> library is given below
fstream file("file_name");
string data;
getline(file, data);
An example of using the function getline() from the fstream class is given below
fstream file("file_name");
char date[20];
file.getline(date, 20);
The second parameter indicates the maximum number of characters that can be
written to the variable data.
The last way that will be discussed in this course is to use the read() function. It is a
safe method for binary data, which will be discussed in the next part of the course.
8
Files – Text Files | FITPED
fstream file("file_name");
char date[20];
file.read(date, 20);
In order to check how many bytes of data have been loaded into the buffer, we use
the function gcount().
file.gcount();
🕮 1.2.3
Now the methods of writing data to a file will be discussed. It should be noted that
we can add the data at the end of the file or overwrite it. It is not possible to add
text between existing data.
First of all, we can write data to a file analogously to the stream cout<<
Data that has been write in this way is always treated as text.
fstream file("file_name");
char data = 'a';
file.put (data);
Another way to write data to a file is to use the function write(). An example of
using the write() function is given below
fstream file("file_name");
string data = "Data to write";
file.write (& data[0], data.length());
The second parameter indicates the number of characters that will be written to the
file.
📝 1.2.4
What commands will allow you to check the state of the stream?
• stream_name.open();
• stream_name.good();
• if(stream_name)
9
Files – Text Files | FITPED
• stream_name.is_good();
📝 1.2.5
How to read data from a file that does not give any information about whitespace?
• stream_name>>variable
• stream_name<|<|variable
• stream_name.getline(variable,1)
• stream_name.read(variable,1)
📝 1.2.6
The use of which function guarantees that data that has been read will not
necessarily be treated as text?
• read
• getline
• get
• put
📝 1.2.7
Which function allows you to specify the number of characters that will be written
to the file?
• put
• read
• write
• getline
📝 1.2.8
10
Files – Text Files | FITPED
📝 1.2.9
1. ifstream file("name");
2. file.put("Great");
3. char data[31];
4. file.read(data, 30);
• line no. 1
• line no. 2
• line no. 3
• line no. 4
Write a code that will read the content of the file "file1.txt" that contains two lines:
The user specifies which character from the file should be displayed on the screen.
If the value provided by the user is too large, display None.
Input : 4
Output: a
Input : 10
Output:
Write a code that will read the content of the given file that contains numbers and
put them into the screen. In case of an empty file return None.
Input : file1.txt
Output: 3,5,1,7,3
Input : file2.txt
Output: 3,3,3,3,3
11
Files – Text Files | FITPED
⌨ 1.3.3 Students
Write a code that will read the content of a given file. The file contains in each line
the name of a student and his/her absence in school in hours. The data is delimited
by a colon. Put the data into two tables and sum all the absence hours and find the
student with the worst attendance. Return also the name of the student and the
average absence. In case of an empty file, return None.
Input : file1.txt
Output: Sum of absence: 80 h; Average: 8.00 h; The worst
attendance: Michal
Input : file2.txt
Output: None
Content of file1.txt:
Content of file2.txt:
⌨ 1.3.4 Grants
Write a code that will read two given text files with the names of students and their
average grades. The average is separated using a semicolon, the averages are
written with a dot. Return the list of names of honoured students - those who have
an average below or equal to 1.4 (we don't need the averages). In case of two
empty files, return None.
Content of file1a.txt:
Content of file1b.txt:
12
Files – Text Files | FITPED
⌨ 1.3.5 Average
Write a code that will return the average of numbers saved in a given text file. Show
the results with one decimal number. The numbers are saved in the file so that each
number is in a separate row. In case of an empty file, return None.
Input : file1.txt
Output: 3.4
Input : file2.txt
Output: None
Content of file1.txt:
1
5
7
3
1
Content of file2.txt:
Write a code that will read the content of a given file that contains names in
separate rows. Return the names starting with the letter B and the name of the
student that is first and last in the file. In case of an empty file, return None.
Input : file1.txt
Output: Barbora Boris Jano Peter
Input : file2.txt
Output: None
Content of file1.txt:
Jano Jana Michal Adam Barbora Andrea Juraj Boris Simona Peter
Content of file2.txt:
13
Files – Text Files | FITPED
Write a code that will read the content of a given file that contains the names each
in separate rows (max. 100). Return the longest and shortest name and the name
that occurs most often. In case of an empty file, return None.
Input : file1.txt
Output: Barbora Eva Jana
Input : file2.txt
Output: None
Content of file1.txt:
Jano
Jana
Michal
Adam
Eva
Barbora
Jana
Andrea
Juraj
Boris
Simona
Peter
Content of file2.txt:
⌨ 1.3.8 Telegram
The text file contains the text of a telegram. Write a code that will return the price of
the telegram when each letter costs 0.10 Euro. Spaces and STOP do not count in
the price. In case of an empty file, return None.
Input : file1.txt
Output: 3.1
Input : file2.txt
Output: None
Content of file1.txt:
14
Files – Text Files | FITPED
Content of file2.txt:
⌨ 1.3.9 Math
Write a code that will read the content of a given file. Each line contains a math
equation with result, for example 11 + 23 = 44, the next line 15*2 = 31 and so on.
There are adding, multiply and subtract. Read the file and return the "fix" of the
equations: if the result is correct, write after the equation "OK", else write "Error:"
and the correct result. After the last equation write a new line with the count of
correct and wrong equations and percentage success. In case of an empty file,
return None.
Input : file1.txt
Output: 1*9=10 Error: 9 5+2=7 OK 7-2=5 OK 3+3=3 Error: 3 1-
0=1 OK Correct: 3 Wrong: 2 Success: 60.0 percent
Input : file2.txt
Output: None
Content of file1.txt:
1*9=10
5+2=7
7-2=5
3+3=3
1-0=1
Content of file2.txt:
⌨ 1.3.10 Numbers
Write a code that will search the given file so that will find all numbers. Let's
assume the numbers are from the words separated by a space from each side.
Return the maximum and minimum number. In case of an empty file, return None.
Input : file1.txt
Output: 3 123
Input : file2.txt
Output: None
15
Files – Text Files | FITPED
Content of file1.txt:
Content of file2.txt:
16
Binary Files
Chapter 2
Binary Files | FITPED
Let's go back to the open function, which was already used in the previous lesson.
The first parameter is a string representing the file's opening path and file name.
The second parameter is optional and can take the following values:
• ios::app, set the file saving position at the end of the file. Data can be saved
only at the end of the file;
• ios::ate, set the file pointer at the end of the file;
• ios::binary, data in the file is treated as binary data, not as text data;
• ios::in, file opened in reading mode;
• ios::out, file opened in write mode;
• ios::trunc, the contents of the file are deleted and replaced with new data.
🕮 2.1.2
If we want to use several options at the same time, we use the symbol | (OR).
The ios::out mode is assigned to objects from the ofstream class by default. The
ios::in mode is assigned to objects from the ifstream class by default. The ios::in |
ios::out mode is assigned to objects from the fstream class by default.
🕮 2.1.3
As was mentioned in the previous lesson, for binary files we do not use cin >> and
cout << streams and get, getline and put functions. Only the use of reading and
writing functions gives correct results for binary files.
18
Binary Files | FITPED
🕮 2.1.4
Examples of using these functions for binary files can be found below
#include <fstream>
int main () {
ofstream file;
file.open("example.bin", ios::out | ios::binary);
if(file.is_open(){
char temp[3];
temp[0]='C';
temp[1]='+';
temp[2]='+';
file.write(temp, 3);
file.close();}
}
#include <fstream>
int main () {
ifstream file;
file.open("example.bin", ios::in | ios::binary);
if(file.is_open(){
char temp[3];
file.read(temp, 3);
file.close();}
}
📝 2.1.5
📝 2.1.6
19
Binary Files | FITPED
📝 2.1.7
In order to open a binary file in write mode and data will be saved at the end of the
file we will use the following flags:
• ios::out
• ios::trunc
• ios::binary
• ios::app
📝 2.1.8
In order to use several flags in the open function, we separate them with a sign
• |
• &
• ,
• ;
📝 2.1.9
• write
• <|<|
• put
• read
📝 2.1.10
• read
• >>
• get
• getline
20
Binary Files | FITPED
📝 2.1.11
• ios::out
• ios::trunc
• ios::in
• ios::app
📝 2.1.12
• ios::in
• ios::out
• ios::trunc
• ios::app
📝 2.1.13
1. ifstream file;
2. file.open ("example.bin", ios::in || ios::binary );
3. char buffer [20];
4. if(file.is_open()){
5. file.read(bufer, 10);
6. file.close();}
• 2
• 1
• 3
• 4
• 5
• 6
📝 2.1.14
• ios::out
21
Binary Files | FITPED
• ios::trunc
• ios::in
• ios::app
Write a code that will read the content of the binary file "file1.bin".
The user specifies which character from the file should be displayed on the screen.
If the value provided by the user is too large, display None.
Input : 4
Output: a
Input : 10
Output: None
Write a code that will read the content of the given binary file that contains numbers
and put them into the screen. In case of an empty file return None.
Input : file1.bin
Output: 3,5,1,7,3
Input : file2.bin
Output: 3,3,3,3,3
⌨ 2.2.3 Students
Write a code that will read the content of a given binary file. The file contains in
each line the length of string and then the string with the name of a student, colon
and his/her absence in school in hours. Put the data into two tables and sum all the
absence hours and find the student with the worst attendance. Return also the
name of the student and the average absence. In case of an empty file, return None.
Input : file1.bin
Output: Sum of absence: 80 h; Average: 8.00 h; The worst
attendance: Michal
Input : file2.bin
Output: None
22
Binary Files | FITPED
Content of file1.bin:
Content of file2.bin:
⌨ 2.2.4 Grants
Write a code that will read two given binary files with the names of students and
their average grades. The average is separated using a semicolon, the averages are
written with a dot. In each line, the length of the string is saved. Return the list of
names of honoured students - those who have an average below or equal to 1.4 (we
don't need the averages). In case of two empty files, return None.
Content of file1a.bin:
⌨ 2.2.5 Average
Write a code that will return the average of numbers saved in a given binary file.
Show the results with one decimal number. In case of an empty file, return None.
Input : file1.bin
Output: 3.4
Input : file2.bin
Output: None
Content of file1.bin:
1 5 7 3 1
Content of file2.bin:
23
Standard I/O Streams
Chapter 3
Standard I/O Streams | FITPED
In the previous lessons, we learned the rules of using text files and binary files. On
this occasion, the following issues were discussed:
🕮 3.1.2
We will continue to discuss the input and output streams. Input-output operations
are defined in the iostream library. Three objects were defined in the iostrem library:
At the iostream input, the types are distinguished, moreover, it is safe in terms of
types and expandable. So cin>>x reads to x according to the type of x. Similarly
cout<<x writes x according to the type of x.
This loop will take a sequence of positive integers separated by whitespaces and
will print them each in a separate line.
As for the files, also in the case of standard input and output, we can use the
functions get, getline, put, read, write.
char sign;
while (cin.get (sign))
cout.put (sign);
Everything that has been read will be displayed on the screen, including spaces.
25
Standard I/O Streams | FITPED
🕮 3.1.3
In C++, a file can be seen as an array of uninterpreted bytes that are indexed from 0
to length-1. Two independent positions are assigned to each stream opened to read
and write:
Only get pointer is assigned to ifstream streams, and only put pointer is assigned to
ofstream streams.
🕮 3.1.4
- tellg - returns a streampos object, points to the place where the data will be read
from the file
streampos tellg();
- tellp - returns a streampos object, points to the place where the data will be written
to the file
streampos tellp();
- seekg - sets get pointer. The definition of this function is given below
The first parameter of the seekg function specifies the number of bytes to move the
get pointer position. The second parameter is optional and specifies the place,
relative to which the position will be moved. The default value is ios::beg i.e. the
beginning of the file. The value ios::cur means the current position, and ios::end
means the end of the file.
- seekp - sets put pointer. The definition of this function is given below
After making the jump to the new position, it is a good practice to check that the
pointer is set correctly. For this purpose, you can use the fail function, which
26
Standard I/O Streams | FITPED
belongs to the fstream class. This function returns the value true if the operation on
the file was unsuccessful.
Another function that can be useful for working with files is the eof function. This
function will return the value true if there is no more data to read in the file.
🕮 3.1.5
An example that presents the use of the functions described above, is presented
below. In this example, the get pointer will be set to the end of the file, while the put
pointer will be in the middle of the file.
#include <fstream>
int main() {
fstream file;
file.open( "file1");
if(file){
streampos begin,end;
begin = file.tellg();
file.seekg (0, ios::end);
end = file.tellg();
file.seekp=((end-begin)/2,ios::begin);
file.close();
}
return 0;
}
🕮 3.1.6
The fstream class has an internal buffer, which is designed to speed up working
with files. When you save data to a file, they are initially saved in the buffer until it is
overflow. This is because access to a given disk area requires a lot more time than
access to the cache memory. There is a function in the fstream class that allows
you to control the internal buffer. The flush function forces the entire buffer
contents to be written to disk, regardless of whether the buffer is full or not.
🕮 3.1.7
27
Standard I/O Streams | FITPED
#include <fstream>
int main(){
fstream file( "file1" );
if( file.is_open() ){
file << "Programming in C ++ is pleasant ";
file.flush();
file<< "and useful";
file.close();
}
return 0;
}
🕮 3.1.8
In the <sstream> header, there are input and output of string streams.
🕮 3.1.9
The standard output can be modified using some functions - manipulators. To use
them, we should attach the <iomanip> or <ios> heading. Manipulators have been
mentioned yet in the input/output format section. They will be described here in
more detail.
28
Standard I/O Streams | FITPED
will display only four digits of the number, that is 3.446e + 005
• cout << boolalpha Uses symbolic representation of true and false (input and
output)
• cout << noboolalpha
• cout << showbase Add prefixes to numbers on the Output: 0 to octal and 0x
to hexadecimal numbers
• cout << noshowbase
• cout << showpoint Always shows a decimal point
• cout << noshowpo
• cout << showpos Shows + before positive numbers
• cout << noshowpos
• cout << uppercase Applies capital letters to the numbers on the output, e.g.
1.2E10 and 0X1A2
• cout << nouppercase
• cout << internal Applies padding according to the designation in the
formatting pattern
• cout << left Completes after value
• cout << right Completes before value
• cout << dec Integer value with base 10
• cout << hex Integer value with base 16
• cout << oct. Integer value based on 8
• cout << fixed Floating point format dddd.dd
• cout << scientific Scientific format d.ddddEdd
• cout << hexfloat Uses a number with base 16 in the mantissa and exponent;
• cout << defaultfloat Uses the default floating point format
• cin >> skipws Skip white characters
• cin >> noskipws
29
Standard I/O Streams | FITPED
• cout << put_money(m, intl) Writes m to cout using the money_put; money_put
specifies types acceptable for m; if intl == true, use standard three-letter
currency names
• cin >> get_time(tmp, fmt) Loads to * tmp in the fmt format and using the
time_get facet of the cin object
• cout << put_time (tmp, fmt) Writes * tmp to the cout according to the fmt
format, uses the time_put facet of the cout object
📝 3.1.10
What does the get pointer, which is assigned to the read and write stream, indicate?
📝 3.1.11
What does the put pointer, which is assigned to the read and write stream, indicate?
📝 3.1.12
Which function returns a streampos object pointing to the place where the data
from the file will be read?
• tellg
• seekp
• seekg
• tellp
📝 3.1.13
Which function allows you to set the put pointer that is assigned to the stream?
30
Standard I/O Streams | FITPED
• seekp
• seekg
• tellg
• tellp
📝 3.1.14
What is the default value of the second parameter of the seekg function?
• ios::beg
• ios::cur
• ios::end
• ios::act
📝 3.1.15
A function that returns the value true if there is no more data to read in the file is
• eof
• fail
• is_open
• good
📝 3.1.16
When we save the data to a file, they are initially saved _____.
• in the buffer
• on the disk
📝 3.1.17
The _____ function of the fstream class ensures that the entire contents of the
buffer are written to the disk.
• seek
• splash
• flush
31
Standard I/O Streams | FITPED
📝 3.1.18
• streampos
• streamoff
• seekdir
• int
📝 3.1.19
• get pointer
• put pointer
Write a code that will calculate the number of characters contained in the given file
(each character should be counted, including newline and space). Put half of the
file's content into the screen. In case of an empty file return Number of characters in
the file: 0.
Input : file1.txt
Output: Number of characters in the file: 9
3
5
1
Input : file2.txt
Output: Number of characters in the file: 9
3
3
3
32
Standard I/O Streams | FITPED
Input : 3 2 /
Output: Error. The result of the operation is not a natural
number.
Input : 3 4 +
Output: 3+4= 7
Write a code that will calculate the sum of the value of items from some store.
Elements are always given according to the scheme: ID number, item name, item
value. Using the property that the standard input recognizes types, check if the
items are correctly entered. The first number is the number of elements.
Input : 4 1000 table 12.5 1002 chair 4.5 1004 bookstand 21.5
1006 box 7.1
Output: The sum of the elements is equal: 45.6
Input : 4 table 1000 12.5 1002 chair 4.5 1004 bookstand 21.5
1006 box 7.1
Output: Error. Incompatibility of types.
Write a code that will read a given text. Return the number of all words and the
longest and the shortest word and the average length of the word in the text. Do not
count the signs ",.?!:;
Input :
Earth treading stars that make dark heaven light:
Such comfort as do lusty young men feel
When well apparell had April on the heel
Of limping winter treads, even such delight
Among fresh female buds shall you this night
Inherit at my house; hear all, all see,
And like her most whose merit most shall be:
Which on more view, of many mine being one
May stand in number, though in reckoning none,
Come, go with me.
Output:
Number of words: 77
The longest word: "reckoning" has 9 chars
The shortest word: "as" has 2 chars
Average length of words :4.36364 chars
33
Standard I/O Streams | FITPED
Input :
The Gardens are bounded on one side by a never ending line of
omnibuses, over which your nurse has such authority that if
she holds up her finger to any one of them it stops
immediately. She then crosses with you in safety to the other
side. There are more gates to the Gardens than one gate, but
that is the one you go in at, and before you go in you speak
to the lady with the balloons, who sits just outside.
Output:
Number of words: 83 The longest word: "immediately." has 12
chars The shortest word: "a" has 1 chars Average length of
words :3.96386 chars
Write a code that will read a given text. Return the number of spaces, tabulators,
newlines, commas, colons, semicolons and dots in the text.
Input :
Earth treading stars that make dark heaven light:
Such comfort as do lusty young men feel
When well apparell had April on the heel
Of limping winter treads, even such delight
Among fresh female buds shall you this night
Inherit at my house; hear all, all see,
And like her most whose merit most shall be:
Which on more view, of many mine being one
May stand in number, though in reckoning none,
Come: go with me.
Output:
Number of space and special characters:
Space: 70
Tab: 0
New line: 10
Dot: 1
Coma: 6
Colon: 3
Semicolon: 1
Input :
The Gardens are bounded on one side by a never ending line of
omnibuses, over which your nurse has such authority that if
she holds up her finger to any one of them it stops
34
Standard I/O Streams | FITPED
Write a code for the Date class with an object of three elements: unsigned short
day, string month and unsigned short year. We assume that the values are given in
this order when creating the object. Overload the input and output operators for this
class so that the object output will be in the form year-day-month.
35
Standard I/O Streams | FITPED
Write a code that will read a given text. Return the number of all rows and the
longest and the shortest row in the text.
Input :
Earth treading stars that make dark heaven light:
Such comfort as do lusty young men feel
When well apparell had April on the heel
Of limping winter treads, even such delight
Among fresh female buds shall you this night
Inherit at my house; hear all, all see,
And like her most whose merit most shall be:
Which on more view, of many mine being one
May stand in number, though in reckoning none,
Come, go with me.
Output:
Number of rows: 10
The longest row has 50 chars
The shortest word has 18 chars
Input :
The Gardens are bounded on one side by a never
ending line of omnibuses, over which
your nurse has such authority that if she holds
up her finger to any one of them it stops immediately.
She then crosses with you in safety to the other side.
There are more gates to the Gardens than one gate,
but that is the one you go in at, and before you go in
you speak to the lady with the balloons, who sits just
outside.
Output: Number of rows: 8
The longest row has 65 chars
The shortest word has 37 chars
Write a code that will read three numbers. The first one defines the system (a
system with a base 8, 10 or 16), the second determines how many characters
should go to the standard output (the missing digits should be filled in *) the third is
the number in a decimal system that we want to write in the given format.
Input : 8 12 12584
Output: *******30450
36
Standard I/O Streams | FITPED
Input : 16 8 87592
Output: ***15628
Write a code that will read a number and will display it with the given number of
decimal places.
Input : 2112.15121566 5
Output: 2112.15122
Input : 1212.151216 10
Output: 1212.1512160000
37
Preprocessor – Directives
and Macros
Chapter 4
Preprocessor – Directives and Macros | FITPED
Directives and macros are used to change the text of a program before it is
recognized by the proper compiler. At the beginning of the line containing the
directive, the sign # should be inserted. At the end of the line containing the
directive, we do not put the sign ; . Directives may be placed on any line of code but
they will be applied to part of the code located below it.
🕮 4.1.2
The two basic commands to define a macro are #define and #undef.
The #define directive is used to exchange one string in the code with a different
string. So if there is a line in the code
then every occurrence of NAME in the rest of the code will be replaced by the "new
value".
The #undef directive is used to delete a macro definition. So if there is a line in the
code
#undef NAME
the macro NAME will be deleted from the rest of the code.
🕮 4.1.3
It is a good practice to write macro names in capital letters. Be careful when using
macros. Macro names can not be overloaded, nor to apply recursion to them.
🕮 4.1.4
#include <iostream>
#define SIZE 20
#define BEGIN {
39
Preprocessor – Directives and Macros | FITPED
#define END }
int main()
BEGIN
int tab[SIZE];
for(int i=0;i<20; i++)
tab[i]=i;
#undef SIZE
#define SIZE 10
int tab1[SIZE];
for(int i=9; i>=0; i--)
tab1[9-i]=i;
return 0;
END
📝 4.1.5
At the beginning of the line containing the directive, the sign _____ should be
inserted.
• #
• @
• \\
• $
📝 4.1.6
• True
• False
📝 4.1.7
• Any occurrence of the X token in the code below the macro will be replaced
by y.
• Any occurrence of the X token in the code will be replaced by y.
• Defining a new variable X, which takes the value of variable y.
• Defining a new variable y, which takes the value of variable X.
40
Preprocessor – Directives and Macros | FITPED
📝 4.1.8
• 50
• 200
• 150
• 250
📝 4.1.9
At the end of the line containing the directive, we put the sign ;.
• False
• True
Define the necessary macros to make the program fill the array so that it contains
cubes of natural numbers (starting from 0 to the value defined by the user).
Input : 1
Output: 0 1
Input : 5
Output: 0 1 8 27 64 125
Compiled_in_CPP.cpp
#include <|iostream>
using namespace std;
//Add the code here
int main()
BEGIN
41
Preprocessor – Directives and Macros | FITPED
int value;
cin>>value;
//Add the code here
char tab[SIZE];
FOR(int i=0;i<|=SIZE; i++)
BEGIN
tab[i]=i*i*i;
cout<|<|tab[i]<|<|" ";
END
return 0;
END
Write a code that using the macro SIZE defines three different tables with a
different length defined by the user. The first array should contain subsequent
natural numbers starting from 0. In the second array, the products of two
consecutive natural numbers should be saved starting from 0. In the third array, the
products of three consecutive natural numbers should be saved starting from 0.
Display the contents of arrays on the screen.
Input : 2 6 8
Output: 0 1
0 2 6 12 20 30
0 6 24 60 120 210 336 504
Input : 5 1 9
Output: 0 1 2 3 4
0
0 6 24 60 120 210 336 504 720
Different_size.cpp
#include <|iostream>
using namespace std;
int main()
{
int value1,value2,value3;
cin>>value1;
cin>>value2;
cin>>value3;
//Add the code here
42
Preprocessor – Directives and Macros | FITPED
int tab1[SIZE];
//Add the code here
int tab2[SIZE];
//Add the code here
int tab3[SIZE];
//Add the code here
return 0;
}
Write code that will calculate the area and perimeter of a circle with a precision of 8
decimal numbers. Define a macro PI that will have PI values with an accuracy of 8
decimal numbers.
Input : 3
Output: Area of the circle: 28.27433385 Perimeter of the
circle: 18.84955590
Input : 4
Output: Area of the circle: 50.26548240 Perimeter of the
circle: 25.13274120
Write a code that allows the user to guess a natural number less than or equal to
100 defined as a macro (equal to 76). If the user specifies the too big or too small
number, please write it. If the user guesses the number, please write
"Congratulations, you guessed the number".
Input : 5
Output: Too small
Input : 16
Output: Too small
Write a code that will allow counting the sum, difference, product and division of
two real numbers. Operation is distinguished by providing values from 1 to 4: 1 for
43
Preprocessor – Directives and Macros | FITPED
sum, 2 for difference, 3 for a product, 4 for division. This should be defined using
macros. The user first gives the number corresponding to the type of operation and
then the two real numbers.
Using the defined directive, it is also possible to define a macro with parameters.
This macro works like a function, of course, it does not recognize types.
🕮 4.3.2
int x=4;
cout<<MULTIPLICATION(x+3);
will display on screen 10, not 14. This will happen because after substitution we get
x + 3 * 2.
44
Preprocessor – Directives and Macros | FITPED
🕮 4.3.3
Therefore, the first multiplication will be made. To avoid such errors, it is good to
include macro arguments in parentheses. So the macro
int x=4;
cout<<MULTIPLICATION(x+3);
🕮 4.3.4
If we use the # operator before the parameter name, the string containing the name
of the parameter will be returned, not its value.
name(Piter);
🕮 4.3.5
If we use the ## operator between two parameters, it will glue two strings.
name(de,Morgan);
45
Preprocessor – Directives and Macros | FITPED
📝 4.3.6
int x=2;
cout<< TEST1(x+5);
• 14
• 4*2+5+1
• 29
• 32
📝 4.3.7
int x=2;
cout<< TEST2(x+5);
• 29
• 12
• 14
• 32
46
Preprocessor – Directives and Macros | FITPED
📝 4.3.8
If in the macro definition we use the # operator before the parameter name, we get
_____.
📝 4.3.9
If we use the ## operator between two parameters in the macro definition, it will
result in _____.
📝 4.3.10
• []
• {}
• #
• &
• ()
• ;
• ,
Write a macro that will calculate the distance that the animal will pass, which runs
with the predefined speed given in m/s for a given number of minutes. Display the
result in kilometres.
Input : 1.4 2
Output: 0.168
47
Preprocessor – Directives and Macros | FITPED
Input : 6 10
Output: 3.6
Define the necessary macro with parameters in order to calculate a trapezium field.
Then use this macro for the parameters' values defined by the user. Display results
on the screen. If one of the defined values is less than or equal to zero, display the
information "Wrong number".
Input : 5 2 3
Output: 10.5
Input : 5 2 2
Output: 7
Define the necessary macro with parameters in order to calculate a triangle field.
Then use this macro for the parameters' values defined by the user. Display results
on the screen. If one of the defined values is less than or equal to zero, display the
information "Wrong number".
Input : 2 1
Output: 1
Input : 3 7
Output: 7.5
⌨ 4.4.4 Interval
Write a macro to see if the given number is from a given interval. Ensure that the
upper and lower bounds of the interval are correctly entered. The first number given
is always the searched one and then are the interval boundaries followed.
Input : 10 2 13
Output: true
Input : 5 15 7
Output: false
48
Preprocessor – Directives and Macros | FITPED
Write a code that will for a given hour (1-12) and period (a.m., p.m.) decide whether
it is a day or a night (let's assume the sun is coming out and sets down at 6:00).
Input : 5 a.m.
Output: night
Input : 3 p.m.
Output: day
We will now discuss a group of macros that are predefined by the compiler and
always available for use. These macros are listed below
• __cplusplus - Defined in C ++ build (but not in C). It can take different values
depending on the C ++ standard. It adopts the value 199711 for ISO C ++
1998/2003, the value 201103 for ISO C ++ 2011 and the value 201402 for ISO
C ++ 2014.
• __DATE__ - Date in format Mmm dd yyyy.
• __TIME__ - Time in hh:mm:ss format.
• __FILE__ - The name of the current file that is compiled.
• __LINE__ - The current line number of the code in the file.
• __STDC_HOSTED__ - The value 1, if the implementation is hosted, i.e. with all
available standard headers; 0 otherwise.
🕮 4.5.2
There is also a group of macros that can be defined depending on whether the
function is available. These macros are listed below
• __STDC__ - In compilers compatible with ANSI or later this macro has the
value 1.
• __STDC_MB_MIGHT_NEQ_WC__ - It has the value 1 if the wchar_t encoding
can give the character a different value than the value of this element as a
regular literal.
• __STDCPP_STRICT_POINTER_SAFETY__ - It is equal to 1 if the implementation
has strict indicator security.
• __STDCPP_THREADS__ - It has a value of 1 if the program can have several
threads.
49
Preprocessor – Directives and Macros | FITPED
The predefined identifier __func__ is also available, but it is not a macro. This
identifier returns the name of the function currently being executed.
Compilers before C99 may not have the __func__ identifier available or may have
another one available but working in a similar way, e.g. __FUNCTION__ for C89.
There are also other predefined macros specific for some compilers, such as
Microsoft compilers, but this topic is beyond the scope of this course.
🕮 4.5.3
#include <iostream>
using namespace std;
int main(){
cout<<__DATE__<<endl;
cout<<__TIME__<<endl;
cout<<__FILE__<<endl;
cout<<__LINE__<<endl;
cout<<__STDC_HOSTED__;
return 0;
}
Apr 1 2019
15:36:10
C:\Users\Project\C\Macra.cpp
📝 4.5.4
• Mmm dd yyyy
• dd:mm:yy
• dd:mm:yyyy
50
Preprocessor – Directives and Macros | FITPED
• mm dd yy
📝 4.5.5
Choose descriptions
__DATE__ - _____
__TIME__ - _____
__FILE__ - _____
📝 4.5.6
📝 4.5.7
51
Preprocessor – Directives and Macros | FITPED
📝 4.5.8
Write a program that, depending on the value of the natural number given by the
user, writes the following information on the screen:
for other values, the program should write "You gave the wrong value".
Input : 1
Output: Predefined_macros.cpp
Input : 2
Output: 199711
Write a function named division that displays on the screen the result of dividing
two numbers. If an error occurs, it displays information about the file name and the
name of the function in which the error occurred.
Input : 5 0
Output: Error in Debug_information.cpp division
52
Preprocessor – Directives and Macros | FITPED
Write a program with an external function that takes a certain double value as a
parameter. At first, the function checks if the compiler is compatible with ANSI or
newer standard and then displays the parameter on the screen with the accuracy of
4 decimal numbers.
Input : 2.12345684
Output: This compiler is compatible with ANSI or newer
standard 2.1235
Input : 52216.125478
Output: This compiler is compatible with ANSI or newer
standard 52216.1255
Write a program that calculates the multiples of the natural number given by the
user, which is smaller than the square of this number. Multiples are saved into a
table with size SIZE. If the table is full, an error message is printed. The message
contains the file name and the reason for the error and is defined by the macro
ERROR(reason).
Input : 5
Output: 5 10 15 20
Input : 15
Output: 15 30 45 60 75 90 105 120 135 150 ERROR in file:
Error_message.cpp Reason: The array size is too small
Define three external functions: sum, difference and product. The user gives the
number 1 if she/he wants to count the sum of two natural numbers, 2 for the
difference and 3 for the product. Then gives two integers for which the operation
should be performed. The program informs the user what function was used and
gives the result of the operation. If the first of the numbers given by the user is
different from 1, 2 and 3, the program displays the message "Enter the number 1, 2
or 3".
Input : 1 4 6
Output: I use the function sum 10
53
Preprocessor – Directives and Macros | FITPED
Input : 2 1 15
Output: I use the function difference -14
54
Conditional Compilation
Chapter 5
Conditional Compilation | FITPED
The #ifdef and #ifndef directives will be discussed first. They are used to exclude or
include part of the code depending on whether the macro specified as a parameter
has been defined (for #ifdef) or not (#ifndef).
#ifdef DISCOUNT
cout<<”Your discount is”<< DISCOUNT;
#endif
The discount amount will be displayed on the screen, provided it has been defined.
If the discount has not been defined, this line of code will be omitted.
#ifndef DISCOUNT
#define DISCOUNT 0.2
#endif
The above fragment defines a discount of 20%, provided it has not been defined
before. If the discount was defined earlier, it leaves its value as it was.
🕮 5.1.2
Now the directives #if, #else and #elif will be discussed. They are used to
determine which fragment of code should be compiled depending on certain
conditions. To define a condition, we can use constants and macros.
#if DISCOUNT>0.5
cout<<”Your discount is large”;
#elif DISCOUNT<0.1
#undef DISCOUNT
#define DISCOUNT 0.3
cout<<”Your discount has been increased”;
#else
cout<<”Your discount has remained the same as it was”;
#endif
56
Conditional Compilation | FITPED
The above fragment of the code for a discount bigger than 50% displays
information on the screen that it is large. The Discount of less than 10% is
increased to 30%. The discount between 10% and 50% is left as it was.
📝 5.1.3
In order to some fragment of code will be executed on the condition that the macro
TEST is not defined, we will use
• #ifndef TEST
• #ifdef TEST
• #undef TEST
• #define TEST
📝 5.1.4
#include<iostream>
using namespace std;
#define VALUE 5
#if VALUE<2
#undef VALUE
#define VALUE 3
#elif VALUE==3
cout<<"Hello";
#else
#undef VALUE1
#define VALUE1 6
#endif
int main(){
cout<<VALUE;
return 0;
}
• 5
• 6
• 3
57
Conditional Compilation | FITPED
• 2
📝 5.1.5
Complete the fragment of code so that the macro LEGS will be equal to 4 provided
it has not been defined before.
_____ LEGS
_____ LEGS 4
_____
• #end
• #else
• #ifndef
• #define
• #if
• #endif
📝 5.1.6
#if VALUE>0
#define VALUE 0
#if VALUE>0
#undef VALUE
#define VALUE 0
#if VALUE>0
#define VALUE 0
#endif
#if VALUE>0
cout<<”Value is 0”;
58
Conditional Compilation | FITPED
#endif
• A
• B
• C
• D
📝 5.1.7
• #endif
• }
• endif
• #end
The __cplusplus macro is defined for C ++ and adopts the following values
depending on the standard: __cplusplus = 199711 for C++98, __cplusplus = 201103
for C++11, __cplusplus = 201402 for C++14. Using a conditional compilation, write
the code which for the year provided by the user gives information whether the
standard in which the program is created is younger, older or exactly from the given
year.
Use phrases: "The C ++ standard is younger than the year you specified.", "The C ++
standard is older than the year you specified.", "This is the year of your C ++
standard.". If the program is not written in C ++, display the information "This is not
C++".
Input : 1994
Output: The C ++ standard is younger than the year you
specified.
Input : 2005
Output: The C ++ standard is older than the year you
specified.
59
Conditional Compilation | FITPED
Write a program that, depending on the value of the natural number given by the
user, writes the following information on the screen:
1: whether the program is written in C standard compatible with the ANSI or newer
4: whether wchar_t encoding may differ from the standard or the macro specifying
wchar_t encoding is not defined
for other values, the program should write "Enter a value from 1 to 4".
Input : 1
Output: C compilation compatible with the ANSI or newer
standard.
Input : 2
Output: Multithreading is allowed.
Write a code with eight functions named from F1 to F8. They are executed
incrementally starting from the value selected by the user. When the function is
executed, the text "Current line is: " and some numbers should be displayed on the
screen. To do this, define a macro named CURRENT_LINE that displays the correct
line number for standards C++11 and C++14. The standard C++98 displays the
correct line number plus 10. The C standard displays the correct line number minus
10.
Input : 8
Output: Current line is: 60
Input : 4
Output: Current line is: 44
Current line is: 48
Current line is: 52
Current line is: 56
Current line is: 60
60
Conditional Compilation | FITPED
Which_line.cpp
#include<|iostream>
using namespace std;
//Add the code here
void F1()
//It should be in line 20
{ CURRENT_LINE; }
void F2() {
CURRENT_LINE; }
void F3() {
CURRENT_LINE; }
void F4() {
CURRENT_LINE; }
void F5() {
CURRENT_LINE; }
void F6() {
CURRENT_LINE; }
void F7() {
CURRENT_LINE; }
void F8() {
CURRENT_LINE; }
int main(){
int temp;
cin>>temp;
//Add the code here
return 0;
}
The access code, which is the number from 1 to 1000, has been defined as a
macro. Define the GUIDE macro, which tells you whether the access code is in the
first quarter (it is a number from 1 to 250), the second quarter (it is a number from
250 to 500), the third or fourth quarter. A code that checks if the user has guessed
the code is given. If so, it writes "Congratulations, you broke the code", if not, it
gives the user a guide.
Input : 125
Output: Third quarter.
Input : 567
Output: Congratulations, you broke the code.
61
Conditional Compilation | FITPED
Access_code.cpp
#include<|iostream>
using namespace std;
#define ACCESS_CODE 567
//Add the code here
int main(){
int temp;
cin>>temp;
if(temp==ACCESS_CODE)
{
cout<|<|"Congratulations, you broke the code";
return 0;
}
GUIDE;
return 0;
}
The average height is 180 cm. Using a conditional compilation, write a program that
calculates the difference between the given height (h) and the average height
(AVGHEIGHT). For people above the average display "You are ? cm higher than the
average.", for others display "You are ? cm lower than the average." If the macro
AVGHEIGHT is not defined, the program should display "The average height has not
been defined.".
Input : 200
Output: You are 20 cm higher than the average.
Input : 160
Output: You are 20 cm lower than the average.
62
Macro assert()
Chapter 6
Macro assert() | FITPED
Within Assert() the expression is checked, if its value is true (1) then the program
will continue to run if the result in assert will be false (0), the program will be
terminated and the user will receive information about where the error occurred (in
which place the error occurred).
#include <assert.h>
#include <iostream>
#include <assert.h>
using namespace std;
int main()
{
int a;
cin >> a;
assert(a!=0);
cout << a;
return 0;
}
In the case when the value of variable a!=0 as a result of the program run, we will
get the value an on the console. For the value of a==0, the program will be
terminated, with a message on the console:
The macro assert() can be used wherever we can expect errors in the operation of
the program. The macro assert() allows us to catch errors before the program will
be able to damage anything.
However, remember to get rid of expressions with the macro assert() in the final
version.
64
Macro assert() | FITPED
📝 6.1.2
• #include <|assert.h>
• #include <|assert>
• #include <|asert.h>
• #define <|assert.h>
📝 6.1.3
#include <iostream>
#include <assert.h>
using namespace std;
int main()
{
int val_1 = 1;
int val_2 = 0;
assert(val_1 == val_2);
cout << val_1;
return 0;
}
• True
• False
🕮 6.1.4
In the final version of the program, you must get rid of the assert() macro. You can
do this by defining the NDEBUG macro
The sample code with the assert() macro disabled will look like this:
#define NDEBUG
#include <assert.h>
int main()
{
int a=1;
65
Macro assert() | FITPED
assert(a==0);
return 0;
}
As a result of the program, the line with the assert() command will be omitted, this
will happen by defining NDEBUG.
🕮 6.1.5
The assert() macro should not be used for expressions that affect the rest of the
program, such as changing the value of a variable. It should be remembered that in
the final version of the program the code inside the assert() macro will not be
executed.
assert(a= 4);
assert(b= a+1);
assert(c++);
📝 6.1.6
Which of the following assert macros are valid (according to the rules of
using assert() macro)
• assert(val == 4);
• assert(val = 4);
• assert(fopen("file.txt","r"))
• assert(sum(a,b) == 0);
📝 6.1.7
In the final version of the program, you can get rid of the assert() macro by defining
a macro:
• NDEBUG
66
Macro assert() | FITPED
• NASSERT
• FINALL
• DASSERT
Write a function that returns the result of dividing (total) of two integers received as
function parameters. The program should be terminated using the assert() macro if
the second of the given numbers is equal to 0.
Input : 4 2
Output: 2
Input : 6 0
Output: Assertion failed: ..., line ...
67
Compilation and Linking
Chapter 7
Compilation and Linking | FITPED
Very often, the concept of code compilation is the translation of code written by a
programmer into a machine and creating a file that can be run on a computer. In
fact, the build process is just one of the processes that the program is prepared to
run.
For C / C ++, the most popular compiler is GCC. It is a set of compilers for various
programming languages developed under the GNU project and made available
under the GPL and LGPL licenses. GCC is just an interface, a controller. GCC (as a
package) consists of many programs, GCC is one of them, it easily manages the
entire process of building a program from beginning to end. Each build phase has
its own application.
In addition to compiling from the IDE environment, we can also compile our
programs from the command line. The easiest way to do this is to invoke the
command:
gcc program_name.c
or
gcc program_name.cpp
• Preprocessing
• Compilation
• Optimization
• Assembling
• Linking
• Make
📝 7.1.2
• Preprocessing
• Compilation
• Cleaning
• Optimization
69
Compilation and Linking | FITPED
📝 7.1.3
To compile a program written in C++ from the command line use the command:
• gcc
• Gcc
• cpp
• gpp
🕮 7.1.4
Preprocessing
The first stage of building the program is the stage called preprocessing (or
precompilation).
This stage is responsible for creating the final program code. At this stage, files
declared with the #include and #define directives, as well as definitions and
macros, are attached. Instead of calling the directive, the code and its contents will
simply be pasted.
The precompilation process itself can be performed by running the command from
the command line:
gcc –E filename.cpp
or
gcc -E filename.c
🕮 7.1.5
Compilation
At this stage, the type code that has been precompiled is converted into assembler
code. In this stage, errors in the source code are also caught and reported to the
user. An assembler file with the extension .s is created. At this stage, elements
such as loops are removed and descended with the usual conditions and goto
instructions. In addition, all constant values are inserted into the code. During
compilation, the code is also adapted to the selected architecture and environment,
i.e. whether it is to be 32 or 64-bit machines, and specific processor technologies
To stop the build process at this level, run the command at the command prompt:
70
Compilation and Linking | FITPED
gcc –S filename.cpp
or
gcc -S filename.c
🕮 7.1.6
Optimization
🕮 7.1.7
Linking
This stage consists of three activities. The first is to search for system libraries or
those indicated by the programmer that has not been defined in the source files.
Simply put, as a result of linking you combine all intermediate files into one
program. In the next stage, the machine code is assigned to the address set. The
last step is to create an ELF (Executable and Linking File) binary executable file
🕮 7.1.8
Make
A system shell program that automates the process of compiling programs that
consists of many dependent files. The program processes the Makefile rules file
and on this basis determines which source files require compilation. This saves a
lot of time when creating the program because as a result of changing the source
file only those files that are dependent on this file are compiled. Thanks to this,
there is no need to compile the entire project. Make is also suitable for other work
that requires the processing of multiple files that depend on each other.
In the simplest case, the command line only contains the word make. The program
then tries to read commands from the control file with the standard name: makefile,
71
Compilation and Linking | FITPED
Makefile or MakeFile. If there is no file with this name in the current directory, an
error is reported. If the control file has a different name, use the following call:
make -f control_file_name
Makefile Rules file for make. Describes the relationship between program source
files. This allows you to process only those files that have changed since the last
build and the files that depend on them. This significantly reduces the time needed
to generate the resulting file. The file format varies depending on the
implementation of the make program, but the basic rules are the same for all
variations of make.
📝 7.1.9
Translation of assembler code into machine code takes place in the stage:
• Assembling
• Linking
• Compilation
• Preprocessing
📝 7.1.10
To perform the preprocessing step itself from the command line, use the command
gcc -E filename.cpp
• True
• False
📝 7.1.11
Blank lines and comments are removed from the code at the stage of:
• Preprocessing
• Compilation
• Assembling
• Linking
72
Compilation and Linking | FITPED
Libraries are files containing code that can be used by other programs. By using
libraries, programs become more modular. The use of libraries also allows for
easier changes and corrections.
In addition to standard libraries, the programmer can also create his own libraries.
• Static libraries - on Windows systems have the extension .lib or .obj., On Unix
systems .a or .o
• Dynamic libraries, on Windows systems .dll, on Unix systems .so
• #include <cstdlib>
• #include <cstdio>
• #include <cstring>
• #include <string>
• #include <new>
• #include <vector>
📝 7.2.2
• .lib
• .a
• .dll
• .cpp
73
Compilation and Linking | FITPED
📝 7.2.3
• .so
• .obj
• .dll
• .a
📝 7.2.4
• C
• C++
🕮 7.2.5
Static libraries
Static libraries are attached to the program at the compilation stage. In order to use
the static library code, information about the library header file that we want to use
should be placed in the code of our program. In the next step, such a library
(actually a code file) should be attached at the stage of compiling the code. The
content of the library is usually located in a binary file, attached during the
compilation of the code.
#include <cmath>
📝 7.2.6
In order to attach a static string library to the program, the following directive
should be added to the program
• #include <|string>
• #include "string"
• include <|string>
• include "string"
74
Compilation and Linking | FITPED
📝 7.2.7
The content of the static library is attached to the program code at the compilation
stage.
• True
• False
🕮 7.2.8
Dynamic libraries
Dynamic libraries in terms of construction are no different from static libraries, their
content is also located in binary files. This means that if you are preparing your own
library, you must compile it into a binary file.
The difference is that dynamic libraries do not have to be loaded when the program
is started. Dynamic libraries can be loaded into the program at any time when the
program is needed. This requires that you write the program properly to handle
library load requests. Dynamic library loading allows creating plugins for the
program.
Dynamic libraries are loaded using the API called dl (dynamic loading). This
interface, which is also a library, contains functions for loading, searching and
removing from the memory of libraries. You can load the library by inserting the
#include <dlfnc.h> header file into your code
The dl interface provides four functions for working with shared objects. They are
dlopen, dlclose, dlsym, dlerror.
The first parameter of the function is the name of the binary file with the library, the
second is the so-called flag.
Sample flags:
• RTLD_LAZY - Perform lazy binding. Only resolve symbols as the code that
references them is executed.
75
Compilation and Linking | FITPED
📝 7.2.9
Dynamic libraries can be loaded into the program at any time during its operation.
• True
• False
Import the math.h and iostream library into the code. So that the program will
compile and run.
76
Additional Topics
Chapter 8
Additional Topics | FITPED
Bitwise operators operate on integer bits. For example, the left shift operator shifts
bits to the left, and the bit negation operator changes each bit with a value of 1 to 0,
and each bit with a value of 0 to 1. In C, there are six-bit operators <<, >>, ~, &, | , ^.
🕮 8.1.2
The value field indicates the integer whose bits are to be shifted, and the shift field
specifies the number of shift bits.
11 << 2
Means shifting all 11 value bits 2 positions to the left. Abandoned places are filled
with zeros and bits shifted outside the given value are skipped.
If you want to change the value of a variable using the offset operator, use the
assignment operator:
x = x << 3
x <<= 3
The right shift operator works in a similar way to shifting the bits to the right.
Syntax:
For example, 14 >> 3 means that all 14 value bits are shifted by 3 places. In the
case of unsigned values, the vacated places are filled with zeros, in the case of
signed values, the vacated places can be filled with zeros or 1 depending on the
character.
78
Additional Topics | FITPED
x = x >> 3
x >>= 3
📝 8.1.3
• >>
• <|<|
📝 8.1.4
Upon execution of the shift operation given below, the value of variable x will be:
unsigned char x = 5;
x <<= 3;
📝 8.1.5
x <<= 2
x = x << 2
• True
• False
🕮 8.1.6
Bitwise logical operators are equivalent to ordinary logical operators, except that
they apply to bit-level values, not to integer values.
The bit negation operator (~) replaces each bit with its opposite (turns 1 into 0 and
0 into 1).
For example
unsigned char x = 3
x = ~ x;
79
Additional Topics | FITPED
We get 252, 3 in a bit write 00000011, after converting each bit to the opposite
value we get 11111100, which gives a decimal value of 252.
The bit operator OR (|) (bit alternative) results in an integer value that is a
combination of two other integer values. Each bit of the new value for which one or
both bits have the value 1 is set to 1, if both corresponding bits have the value 0,
then the result bit is set to 0.
For example:
unsigned char x = 3;
unsigned char y = 4;
unsigned char with;
z = x | y;
For the given example, the value z will be 7, because 3 in the bit write is 00000011,
4 in the bit write is 00000100. In the resulting number, the bits for which the input
values appeared in at least one case 1 supplement 1, the remaining 0, hence the
result actions in bit form are 00000111, i.e. 7.
The bit operator XOR (^) (bit symmetric difference) results in a value where each bit
for which one (but not both) of the corresponding bits of the original value is equal
to 1, is set to 1. If both corresponding bits are equal to 0 or both are equal to 1, the
result bit is set to 0.
For example:
unsigned char x = 5;
unsigned char y = 4;
unsigned char with;
z = x ^ y;
For the given example, the value of z will be 1, because 5 in the bit write is
00000101 and 4 is 00000100, after performing the XOR operation we get in the bit
write 00000001, i.e. 1.
The bit operator AND (&) (bit conjunction) gives the result a value for which each bit
for which both corresponding bits of the original values are equal to 1 is set to 1,
the others to 0.
For example:
unsigned char x = 5;
unsigned char y = 4;
unsigned char z;
z = x & y;
80
Additional Topics | FITPED
📝 8.1.7
• True
• False
📝 8.1.8
• OR
• AND
• XOR
📝 8.1.9
As a result of the code below, the variable x will take its value:
int main()
{
unsigned char x = 11;
x = ~x;
return 0;
}
Write a bit shifting program to the left. The number to shift and the shift value is to
be entered into the program from the keyboard.
Input : 13 3
Output: 104
81
Additional Topics | FITPED
Input : 8 1
Output: 16
Write a program that performs an OR bit operation on two numbers entered from
the keyboard.
Input : 10 1
Output: 11
Input : 8 5
Output: 13
There are sometimes cases when at the stage of creating a function we do not
know the exact number of arguments we would like to pass to it.
The second option is that you want to create a function to which you can send a
different number of arguments. For example, we want to set a maximum value for
2, 4, 10 numbers, or display the values of a certain number of arguments.
We declare variadic functions with an ellipsis (...) in the place of parameters, we put
all mandatory parameters before the ellipses, for example:
It declares a function that can be called with the mandatory first argument of type
int * and any number of additional arguments.
For example
82
Additional Topics | FITPED
📝 8.3.2
📝 8.3.3
• True
• False
🕮 8.3.4
To access the arguments of a function from within a function, use the macros:
#include <cstdarg>
int sum_of(int number, ...){
int sum = 0;
va_list args;
va_start(args, number);
83
Additional Topics | FITPED
Usage:
sum_of(1,2) // Output 3
sum_of(2,4,6,7) // Output 19
Variadic functions may be useful because of their versatility, but the problem is the
lack of control over the correctness of arguments passed to the function. The
variadic function should be used with caution and only when necessary.
📝 8.3.5
• <|cstdarg>
• <|variadic>
• <|cstdvar>
• <|cstd>
📝 8.3.6
• False
• True
📝 8.3.7
• va_end
• va_stop
• va_arg
• va_fin
84
Additional Topics | FITPED
Write a variadic function that calculates the average value of the numbers entered.
Input : 4 2
Output: 3
Input : 8 10
Output: 9
Write a variadic function that accepts any number of strings, and as a result returns
a joined string consisting of strings given as arguments, separated by a comma,
omitting strings beginning with the letter -a-. The first argument of the function is
the number of strings to be given in the function-s arguments. Strings are to be
entered from the keyboard.
85
Namespaces
Chapter 9
Namespaces | FITPED
The namespace is a feature of the C++ language that allows you to write large
programs using code from different sources. We can imagine that we have two
packages from different suppliers - Comp_A and Comp_B, in both packages there is
the sum() function. If we call the sum() function, the compiler will not know which
function we want.
Let's assume now that both companies have placed their functions in namespaces
with a name compatible with the name of the company, and in order to call the
function provided by Comp_A we will call it as:
comp_A::sum();
comp_B::sum();
Also, classes, functions and variables that are standard components of the C++
compiler are placed in the namespace, for example, we use iostream.h, with the std
namespace, in which we have available for example std::cout, std::cin, std::endl .
For example, if you want to use the std namespace, you can use:
Then the screen display with cout will look like this:
87
Namespaces | FITPED
📝 9.1.2
• namespace::function();
• namespace:function();
• namespace function();
• namespace..function();
📝 9.1.3
• False
• True
📝 9.1.4
🕮 9.1.5
In addition to the available namespaces, you can also define your own namespace.
Thanks to this solution, names from one namespace do not conflict with identical
names declared in other namespaces. The namespace keyword is used to create
your own namespace.
namespace Ex1{
int var1;
void sum(int *tab);
double mean;
}
namespace Ex2{
double var1;
void sum(int *tab){
...
}
void view();
88
Namespaces | FITPED
For example, to place the code of function sum(int * tab), simply refer to the
namespace anywhere and place the function code there.
Namespace Ex1 {
void sum (int * tab) {...}
}
Calling the function sum(int * tab) for the Ex1 namespace will look like this:
Ex1::sum(tab);
We can also indicate that we will use functions or variables from a given
namespace through the keyword using.
int main () {
using Ex1 :: var1;
cin >> var1; // we refer to the variable from the
Ex1 namespace
}
📝 9.1.6
• False
• True
📝 9.1.7
To use a single variable from a namespace without having to precede it each time
with what namespace it comes from, you can use the command:
• using namespace::variable;
• namespace::variable;
• using ::variable
• using namespace namespace::variable;
89
Namespaces | FITPED
🕮 9.1.8
The std::cin is an input stream for loading data into variables. It belongs to the std
namespace, to use it you must import the iostram library. In order for data to be
read in using std::cin, the operator >> must be used for this, reading the data looks
like this:
#include <iostream>
...
int a;
std::cin >> a;
When using the cin stream, whitespace (space, tab, enter) is ignored, they are
treated as data splits, so when you try to write to a string variable using the cin
string "Example of using cin" for variables, only the first word will be written (
"Example").
The std::cin stream also allows you to enter multiple data using one cin stream,
subsequent variables for which the data is to be read are switched by the operator
>>, e.g.
int a, b, c;
std::cin >> a >> b >> c;
The cin stream also allows error checking, using the fail() method, which I call after
loading the data:
int a;
std::cin >> a;
cout << std::cin.fail();
This method will work when, for example, a program user gives a character instead
of a number.
Entering incorrect data and calling an error does not lead to their deletion from the
buffer, these data remain in the buffer and will be written to the variable the next
time the std::cin stream is called; To remedy this, discard the buffer data using the
std::cin.ignore() method.
90
Namespaces | FITPED
🕮 9.1.9
The std::cout is a stream used to output variable values to the outside (e.g. to
console). The cout stream connects to the operator "<<" to output data:
int a = 4;
std::cout << a;
The values of several variables can be derived using one cout stream:
The cout stream also has functions and operators for modifying the format of the
data displayed, the following inland includes:
📝 9.1.10
📝 9.1.11
To display the value of several variables using one cout command, we will use:
📝 9.1.12
• cin.ignore();
91
Namespaces | FITPED
• ignore(cin);
• cin.reject();
• reject(cin);
Write a program in which your own namespace will be declared. Within the created
namespace, declare checking if the triangle whose length is given by the user is a
right triangle. The result of the function is to be true or false. Call the function in the
main function, display the result of its operation.
Input : 6 3 7
Output: false
92
String
Chapter 10
String | FITPED
10.1 String
🕮 10.1.1
In the current C++ standard, the string class has been added. The string class
allows you to store strings not in character arrays, but in objects of this class. The
use of the string class to store strings simplified string operations compared to
operations on character arrays.
To use the string class, attach the string header file. The string class is part of the
std namespace, so you must use the using-declaration or refer to it as std::string.
🕮 10.1.2
The basic difference between string objects and character arrays is that we create
string objects as normal variables, not as arrays. Using the string class also allows
you to transfer responsibility for resizing the chain to the program. The program
automatically increases the length of the string object as we add more characters
to it.
std::string str1;
std::cin>>str1;
Concatenation of strings:
94
String | FITPED
Comparison of chains
str1.empty ();
Str1.swap(Str2);
95
String | FITPED
📝 10.1.3
• std::string text;
• std::String text;
• std::string="Some text";
• std::string[] string="Some text";
📝 10.1.4
• True
• False
📝 10.1.5
You can work on objects of the String class like regular variables.
• True
• False
📝 10.1.6
• str1 += str2;
• str1.add(str2);
• str1 = add(str1, str2)
• str1.copy(str2);
📝 10.1.7
96
String | FITPED
#include <iostream>
using namespace std;
int main()
{
string text = "Some example text";
cout << text[0];
return 0;
}
• S
• Error - the program will not compile
• Some example text
• Na
📝 10.1.8
After using the command text.erase(1, 2), what value will the string variable text
store?
Write a program that will display the given string (given by the user), skipping every
second letter for it.
Input : "Example"
Output: "Eape"
Input : "Apple"
Output: "Ape"
⌨ 10.2.2 Is upper
Write the function first_Upper(), which will check if the first letter of the string given
as the function parameter is uppercase. The function returns true if it is, or false
97
String | FITPED
otherwise. In the main function call your function, strings are to be typed from the
keyboard.
Input : "Example"
Output: true
Input : "example"
Output: false
Write a program that reads a string from the user and then creates a string that is
the inverse of the given string and displays it on the screen.
Input : "Example"
Output: "elpmaxE"
Input : "apple"
Output: "elppa"
⌨ 10.2.4 Palindrome
Write a program that reads a string from the user and then checks to see if the
string is a palindrome. The program displays true if it is or false if not.
Input : "Example"
Output: false
Write a program that reads a string of characters from the user and then displays
information about how many times the last character is repeated in that string.
Input : "Example"
Output: 2
98
String | FITPED
Input : "banana"
Output: 3
99
Exercises
Chapter 11
Exercises | FITPED
11.1 Exercises
⌨ 11.1.1 Operator overloading - Inventory class
Write a code for the inventory class with an object of three elements: int ID, string
name and double value. We assume that the values are given in this order when
creating the object. Overload the input and output operators for this class so that
the object output will be in the form
Input : 4
1000 table 12.5
1002 chair 4.5
1004 bookstand 21.5
1006 box 7.1
Output: <1000,table,12.5euro>;
<1002,chair,4.5euro>;
<1004,bookstand,21.5euro>;
<1006,box,7.1euro>;
Input : 4
table 1000 12.5
1002 chair 4.5
1004 bookstand 21.5
1006 box 7.1
Output: Error. Incompatibility of types
101