0 ratings0% found this document useful (0 votes) 227 views80 pagesC Python Tricks and Tips - 17th Edition 2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Next level secrets
and fixes get to the
heart of the C++
coding language
We share our
awesome tips and
shortcuts for coding
Python and C++
Advanced guides
and tutorials for
programming with
C++ & Pythonsave a whopr ‘1
e
5% Off
ee Lely
with 26) Papercut
=
me
iPhone Weave
Guidebook
®
Ce eeh
Lae Cor io ue
peace emcee)
Not only can you learn new skills and master your
tech, but you can now SAVE 25% off all of our coding
and consumer tech digital and print guidebooks!
Simply use the following exclusive code at checkout:
NYHF23CN
www.pclpublications.comUES
a LAS
C++ & Python Tricks & Tips is the perfect digital publication
for the user that wants to take their skill set to the next
level. Do you want to enhance your user experience? Or
wish to gain insider knowledge? Do you want to learn
directly from experts in their field? Learn the numerous
short cuts that the professionals use? Over the pages of this
essential advanced user guide you will learn everything you
will need to know to become a more confident, better skilled
and experienced owner. A user that
will make the absolute most of
their coding use and ultimately Over the page
the platforms themselves. Our Journe, e
&y Continues
An achievement you can and we will be with S,
earn by simply enabling us at ever, amar ct
‘Y stage to adui.
to exclusively help and inform and ‘ vise,
teach you the abilities we inp itimately
have gained over our decades ‘pire you to
of experience. 90 Further.Contents me
Orn kc) One)
Lists While Loop
10 Tuples 58 ForLoop
12 _ Dictionaries 60 Do... While Loop
14 Splitting and Joining Strings 62 IF Statement
16 _ Formatting Strings 64 If... Else Statement
18 Date and Time
20 _ Opening Files oe
22 Writing to Files PA Ria k eke
24 _ Exceptions
68 Common Coding Mistakes
26 Python Graphics
70 _ Beginner Python Mistakes
72__ Beginner C++ Mistakes
& Using Modules 74 Where Next?
30 Calendar Module
32 OSModule
34 Random Module
36 Tkinter Module
38 Pygame Module
42 Create Your Own Modules
44) C++ Input/Output
46 _ User interaction
48 Character Literals
50 Defining Constants
52__ File Input/Output
—( Contents Cl
.
4 2. tal of the most
powerful and versatile
programming languages available,
Python and C++ and broken them
down into bite-sized tutorials and
& guides to help you learn how
they work, and how to make them
work for you...”TT
Working with Data)Working
Vaan Dye] er-
Peer tai mW un seth Ke
Ceol cel MELO ECR nek
Python to your every demand. Over these
RoE Re Ole ela a elke)
fare )eo Ma) (ome (tea ENR
CTU Le co}
Peterlee Rime ie CLs
Then, you can learn how to use date and time
Functions, write to Files in your system and
even create graphical user interfaces that take
your coding skills to new levels and into new
Polke) rad (ol
CeZz » Working with Data
:
Lists
Lists are one of the most common types of data structures you will comes across in
Python. A list is simply a collection of items, or data if you prefer, that can be accessed
as a whole, or individually if wanted.
WORKING WITH LISTS
Lists are extremely handy in Python. A list can be strings, integers and also variables. You can even include Functions in lists,
and lists within lists.
EEG EDD Alissa sequence of data values calleditems. You [BETESEWM You can also access, or index, the last tem in alist by
create the name of your lst followed by an equals Using the minus sign before the item number Et),
‘sign, then square brackets and the itemns separated by commas; or the second to last item with [-2] and so on. Trying to reference an
note that strings use quotes: item that isn’t in the list, such as [10] will return an error:
numbers = [1, 4, 7, 21, 98, 156] numbers[-1]
mythical_creatures - [“Unicorn”, “Balrog”, mythical_creatures[-4]
“Vampire”, “Dragon”, “Winotaur™]
FETED orxe you've defined your list you can call each FTE DD tiing is similar to indexing but you can retrieve
by referencing its name, followed by a number. Lists multiple tems in a ist by separating item numbers
start the firsttem entry as 0, Followed by 1,2, 3 and soon. ‘with a colon. For example:
For example: nunbers[1:3]
Lalaiecas ‘will output the 4 and 7, being tem numbers 1 and 2. Note that the
To call up the entice contents of the lst. returned values don't include the second index position (as you
‘would numbers{t:3] to return 4,7 and 21),
punbers[3]
‘Tocall the third From zero temin the lst 21 in this case).‘You can update tems within an existing list, eemove
items and even join lists together. For example, to
join two lists you can use
everything = nunbers + mythical_creatures:
‘Then view the combined list with:
everything
BTID cers can be added to a list by entering:
nunbers-nunbers+[201]
Or forstrings:
nythical_creatres=nythical_creatures+[*Griffin"]
‘Or by using the append Function
nythical_creatures .append(“Nessie”)
‘nunberss. append(278)
Removal of items can be done in two ways. Te First
Is bythe tem number:
del nunbers[7]
‘Alternatively, by tem name:
inythical_creatures.renove("Nessie”)
‘You can view what can be done with lists by entering
>>>>>>>>Leap Year
Calculatorccecccecee\n” )ylaintCinput“Enter the
first year: “))
y2nintCinput(“Enter the second year: “))
Veaps=calendar.Leapdays(y1, y2)
print(“Nunber of Leap years between”, yl, “and”,
ye, “is”, Leaps)
‘You could even fashion that particular example into
‘apiece of working, user interactive Python code:PPID You can alco create a program that will display all
the days, weeks and months within a given year:
import calendar
year=intCinputC“Enter the year to display: “)
print(calendar.preal(year))
|We're sure you'll agree that’s quite 3 handy bit oF code to have
tohand.
Interestingly we can aso lst the number of daysin 2
‘month by using a simple For loop:
import calendar
cal=calendar. TextCalendar(calendar -SUNDAY)
for i in cal.itermonthdays(2018, 6):
print(i)
fe tm onto ro
BAR cos cvuicurgicciomematc
BERD wosccsocstonescemina
referee poten aren
month. So the counting ofthe days will start on Friday 1st June
2018 and will total 30 as the output correctly displays.
(Calendar Module ( CG
BETeEED You're also able to print the individual months or
days ofthe week
import calendar
for name in calendar month name:
printCname)
‘import calendar
for name in calendar .day_name:
print(nane)
PPD The calendar module also allows us to write the
Functionsin HTML, so that youcan display iton a
website. Let's start by creating a new file
import calendar
cal=open(“/hone/pi/Document's/cal .htmL”
cecalendar .HTMLCalendar(calendar . SUNDAY)
cal.write(c. formatmonth(2018, 1))
cal -close()
‘This code wil create an HTML file called cal, openit witha browser
and it displays the calendar for January 2018.
Te EREE 0f course, you can modify that to display a given,
year asa web page calendar:
‘import calendar
year=int(input(“Enter the year to display as a
webpage: “))
cal=open(“/home/pi/Documents/cal.html”, “w")
cal .write(calendar.HTMLCalendar(calendar..MONDAY).
formatyear(year))
cal.close()
‘This code asks the user fora year, then createsthe necessary
‘webpage. Remember to change your File destination,z=) Using Modules)
OS Module
INTO THE SYSTEM
One of the primary Features of the OS module is the ability to list, move, create, delete and otherwise interact with files
stored on the system, making it the perfect module for backup code.
ESTED voucan startthe 0s module with some simple PETER the windows output isifferent as that's the
Functions to see how it interacts with the operating current working directory of Python, as determined
system environment that Python is running on. IFyou'e using Linux by the system; as you might suspect, the os.getcwd( Function is
orthe Raspberry Pty his asking Python to retrieve the Curent Working Directory Lnuuses
villse something along the same nes asthe Raspbery Pas wil
SoPEREEE maxcosusers mene
hone-os..getowd()
printchane)
Tretuedreitrompatngtniie tone REM ere reenter te OS male
eleiZ is the current user's home folder on the system. ued is its ability to launch programs that are installed
Inour example that's home/oiitwillbe different depending on _in the host system. For instance, iFyou wanted to launch the
the user name you lag in as and the operating system you use. Chromium browser From within a Python program you can use
For example, Windows 10 will output: C\Program Files (x86)\| the command:
Python36-32.
import os
5 browser-os..system(“/usr/bin/chromium-bronser")The os system) function s what allows interaction
with external programs; you can even call up
previous Python programs using this method. You will obviously
need to know the ful path and program filename for it to work
successfully, However, you can use the following:
import os
os.systen(‘start chrome “https://mmw.youtube.con/
Feed/music”?)
FETED £0" Step 5's example we used Windows, to show
that the OS module works roughly the same across
allplatforms. In that case, we opened YouTube's music Feed page, so
itis therefore possible to open specific pages:
import os
os.system(‘chromium-browser “http://
bbdmpublications .com/"*)
Perea Note in the previous step's example the use of
single and double-quotes. The single quotes encase
the entire command and launching Chromium, whereas the double
‘quotes open the specified page. You can even use variables to call,
multiple tabsin the same browser:
import os
‘-(‘chromium-browser “http://bdnpubl ications.
con/”?)
b=C‘chromium-browser “http: //ww.google.co.uk”?)
‘os. system(a + b)
(0s Module cH
‘The ability to manipulate directories, or folders if
{you prefer, is one of the OS module's best features
For example, to create a new directory you can use:
‘import. os,
fs. mkdi rC*NEW")
This creates a new directory within the Current Working Directory,
named according to the object the mkdir Function.
You can also rename any directories you've created
by entering
STEP 9
import os
os.rename(“NEW", “OLD")
To delete them:
‘import. os,
os.rmdirr(*OLD")
—_———_
‘Another module that goes together with OS is
shutil You can use the shutil module together
with OS and time to create a timestamped backup directory, and
copy ies into:
‘import os, shutil, time
root_sre_dir = r*/home/pi/Document's”
root_dst_dir = ‘/hone/pi/backup/? + time-asctime()
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_srcdir, root_
dst_dir, 1)
if not os.path.exists(dst_dir
os .makedirs(dst_dir)
for file_ in files:
src_file = os.path.join(src_dir, file)
dst_file = os.path. join(dst_dir, file)
if 05.path.exists(dst_file):
os.renove(dst_file)
shutil.copy(src_file, dst_dir)
print(“s>ss>sss>>Backup completeccecceRandom Word Finderceceeccece”)
primt(“\nUsing a 466K English word text file I can
pick any words at randon.\n”)
nds-int(input("\nHow many words shall I choose?
»
with openc“/hone/pi/DowniLoads/words. txt”, “rt”) as,
t
words = f.readlines()
words = [w.rstrip() for w in words]
print¢* 2
for w in random.sanple(words, wds):
print(w)a ) Using Modules )
Tkinter Module
GETTING GUI
‘Tkinter is easy to use but there’s a lot more you can do with it. Let’s start by seeing how it works and getting some code into it
Before long you will discover just how powerful this module really is.
“gers aly bit no Python, However es
ous4) available when you enter: import tkinter, then
youneedtopip install tkinter from te command promet
We canstart to mport modules ferent thn before tosaveon
‘ying and by importing al ther contents
import tkinter as tk
from tkinter import *
PPE DD snot recommended to import everything from a
module using the asterisk butt won't do any harm
normally. Let's begin by creating abasic GUI window, enter:
wind-TkO)
‘This creates a small, basic window. There's nat much else to do at
this point but click the Xin the comer to close the window.
‘The ideal approachis to add mainloop( intothe
SMD et conrctheThter event op, but vel
sgetto that soon, You've just created a Tkinter widget and there are
several more we can play around with:
btn-ButtonC)
btn.packQ
btn["text®:
The first line Focuses on the newly created window. Click back into
the Shell and continue the other lines.
Hello everyone!”
Ft
ow ar
PEED You can combine the above into a New File:
import tkinter as tk
from tkinter import *
btn-ButtonC)
btn.packQ
btn[text””
Then add some button interactions:
def clickQ:
print(*You just clicked me!
btn{"“conmand™}=click
Hello everyone!”Save and execute the cade from Step 4 and a
window appears with ‘Hello everyone inside. IFyou
lick the Hello everyone! button, the Shell will output the text ‘You
just clicked met. t's simple but shows you what can be achieved
with a Few tines of code,
You can also display both text and images within
a Tkinter window. However, only GIF, BGM or PPM
formats are supported. Sond an image and convert it before using
the code. Here's an example using the BOM Publishing logo:
from tkinter import *
root = TkO,
Logo = Photolmage(file=”/hone/pi/Downloads/B0M_logo.
Gif”)
Wi = Label(root, root.titleC“B0M Publications”),
‘image=Logo). pack(side="right”)
content = “** From its hunble beginnings in 2004,
‘the BOM brand quickly grew from a single publication
produced by a team of just two to one of the biggest
anes in global bookazine publishing, for two simple
reasons. Our passion and commitment to deliver the
very best product each and every volune. While
‘the company has grom with a portfolio of aver 250
publications delivered by our international staff,
‘the foundation that it has been built upon remains,
the sane, which is why we believe BOM isn’t just
the first’ choice it's the only choice for the smart.
consumer. “”*
w2 = Label(root,,
justify-LeFT,
padx = 10,
‘text=content).pack(side~"LeFt”)
root mainloop()
The previous codes
‘quite weighty, mostly
‘due to the content
variable holding a part
of BOM's About page
from the company
website. Youcan
‘obviously change the
content, the root ttle
{and the image to suit
your needs
BETEEE DD You con create rai buttons too. Try
from tkinter import *
root = Tk,
v = IntVar()
LabelCroot, root. titleC“Options”), text="""Choose
@ preferred language:”*”,
Justify = LEFT, padx = 20).pack()
RadiobuttonCroot,
‘text-"Python”,
padx = 20,
variable=v,
value=1) .packCanchor=W)
variable-v,
value=2).packCanchor=W)
maintoop()
You can also create check boxes, wth buttons and
Siar)
‘output to the Shel
from tkinter import *
root = Tk,
def var_states():
print(*Warrior: %d,\nMage: Kd” % (varl.getQ),
var2.getQ))
Label(root, root. titleC“Adventure Gane”),
text~">>>>2>>>>2Your adventure roleccc File) and create a True/False while loop:
‘import pygame
from pygane. locals import *
pygane.init()
ganewindow=pygane display. set_node((800, 600))
pygane. dispLay.set_caption(“Adventure Gane”)
running-True
while running:
for event in pygane.event.get():
if event. type=-QUIT:
running-False
pygane. quit)
fle Est Farmat_ Bun tions Windows. Hep
eerandoeytane splays nade 800600)
SF event. SypenstutTBRED the Pyaame window still won't
dose don't worry, it's ust a
discrepancy between the IDLE (whichis written
with Tkinter) and the Pygame module. I you
run your code via the command ne, It closes
perfectly well
ESRD You're going to shift the code around a bit now,
running the main Pygame code within a while loop;
itemakes it neater and easier to Follow. We've downloaded a graphic
touse and we need to set some parameters for pygame:
import pygame
pygame.imt)
while running:
gamewindow=pygane .dispLay. set_mode((800,600))
pygane.display.set_caption(“Adventure Gane”)
black-(0,0,0)
white=(255,255,255)
PEPPD cx's quickly go through the code changes. We've
defined two colours, black and white together
with their respective RGB colour values, Next we've loaded the
To pene
1 pgane locals oper *
‘ganerindon-pygane. splay .set_mode((800.600))
Breone display. setccoption-Aaventore cane")
Biseke(0.0-0).
sntten( 258,235,255)
“ngspyeae. image Load“ /hone/p3/Oonnlosds/sprive} eng")
et spritece 5
( Pygame Module cl
‘img-pygane image. Load(/home/pi/Downloads/
spritel png”)
def sprite(x,y):
ganewindow.blitCing, Ox,y))
x-(800*0.45)
y=(600"0.8)
gamewindow -fiLLCwhitte)
sprite(x,y)
pygame..display.update()
for event in pygane.event .get():
if event. type=-pygame.QUIT:
running-False
downloaded image called spritet.png and allocated it to the
variable img; and also defined a sprite Function and the Blt Function
will allow us to eventually move the image.
(8000.45)
yrts00"0"8)
ganenrindon.£111(t6)
Sprstecxey)
Preane, display update)
for event in pygane.event.get(
SF event yper=qurr
rumingeraise
PramesauitOUsing Modules )
FETTER) Now we can change the code around again, this imgspeed=0
time containing a movement option within the
hile loop, and adding the variables needed to move the sprite
‘around the screen:
while running:
for event tn pygone.event.get():
‘if event.type==QUIT:
import pygane running-Patse
speateeenerl oss eniwart if event. type = pyacme,KEYDOM:
j {f event.Rey--pygane. CLEFT:
running=True xchange
_gamewindow=pygane. display. set_mode((800, 600)) ELLER EEE KESS=PHGOMNEFKORTGITE
fvoane, display set-captionC*Adventure Gane")
ceed ‘fF event. Rey==pygane.K.LEFT or event
{ng-pygane image. Load(*/hone/pi/Domnloads/spriter, KeY=-Pygane. K RIGHT:
png”) xchange=0_
def sprite(x,y): x += xchange
ganewindow.blitCina, Cx.y)) ‘amewindow.fU1Cahite>
‘+ sprite(x,y)
yocen0"0:8) pygame.display.update()
xchange pygame. quit)
BETTER) Copy the code down and using the left and right arrow keys on the keyboard you can move your spite across the bottom of
the screen, Now, itlooks like you have the makings of a classic arcade 2D scroller inthe works.You can now implementa Few additions and utlise
some previous tutorial code, The new elements are
the subprocess module, of which one Function allows usto launch
‘second Python script from within another; and we're going to create a
New File called pygametxt py:
import pygane
import time
import subprocess
( Pygame Module cl
Pygane. display ip)
clock. tick(60)
continue
break
pygame.quit()
pygane. init)
screen = pygame.display. set_mode((800, 250))
clock = pygane.time.Clock()
font = pygame.font.Font(None, 25)
Pygane. tine. set_timer(pygane.USEREVENT, 200) |
def text_generatorCtext): |
tm = 0
for letter in text:
‘tmp += letter
if letter I=
yield tp
class DynanicText(object):
def _init_(self, font, text, pos,
autoreset-False):
self.done = False
self.font = font
self.text = text
self._gen = text_generator(self. text)
self.pos = pos
self.autoreset = autoreset
self updateQ)
def reset(self):
self._gen = text_generator(self. text)
self.done = False
self update)
def update(self):
if not self.done:
try: self.rendered = self. font.
render(next(self..gen), True, (0, 128, 0))
‘except Stoplteration:
self.done = True
time.sleep(10)
subprocess. Popen(“python3 /home/pi/Documents/
Python\ Code/pyganel.py 1”, shell-True)
def dran(self, screen):
screen.blit(self.rendered, self.pos)
text=(“A long time ago, a barbarian strode from the
frozen north. Sword in‘hand. ..”)
message = DynamicText(font, text, (65, 120),
‘autoreset=True)
while True:
for event in pygame.event .getQ:
if event.type == pygane.QUIT: break
if event. type — pygame.USEREVENT: message.
vedate()
screen.fill(pygane.color.Color( black’)
message.dran(screen)
When you run this code it wil display a tong,
narrow Pygame window with the intro text
scrolling to the right. After a pause often seconds, itthen launches
the main game Python scriot where you can mave the warrior sprite
around, Overall the effect is quite goad but there's always room
For improvement.z=) Using Modules )
Create Your Own Modules
BUILDING MODULES
Modules are Python files, containing code, that you save using a .py extension. These are then imported into Python using the
now Familiar import command.
FETED cts start by creating a set of basic mathematics
‘square or raise a number to an exponent (power). Create a New File
in the IDLE and enter:
def timestwo(x):
return x * 2
def timesthree(x):
return x * 3
def square(x):
return x
def poner(x,y)
return x ** y
Under the above code, enter Functions to callthe
code:
print Ctimestwo(2))
print (timesthree(3))
print Csquare(4))
print (power(5,3))
‘Save the program as basic_math.py and execute itto get the results.
Now youre goingto take the function defintions
oz) ‘out of the program and into a separate file.
Hghlght the function dfintons and choose EG» Cut. Choose Fle
= New File and use Ede> Paste nthe new window, You now have
two separate es, one with the function defnkion, the oer ith
the funtion alls
PETER you now try and execute the basic math py code
‘again, the error ‘Namerror: name timestwo' is
not defined’ will be displayed. This is due to the code no longer
having access to the function definitions.
TED Return tothe
newly created
window containing the Function
definitions, and cickFile> Save |= :
As. Name this minimath.py
and save it in the same location
a the original basic_math,
y program. Now close the
Iminimath.py window, sothe
basic. math.py window islet
open.Back to the basic math py window: at the top of the
code enter:
from minimath import *
‘This willimport the Function definitions asa module, Press FS to
save and execute the program to see tin action
‘Youcan now use the code Further to make the
programa little more advanced, utilising the newly
‘created module to its ful. Include some user interaction. Sart by
‘eating a basic menu the user can choose from:
print(“Select operation.\n”)
print(“1.Times by two”)
print(*2.Times by Three”)
printC*3.Square”)
print(“4.Power of”)
choice = input(“\nénter choice (1/2/3/4):")
FER vec cnssotcvsrneuoseuiennc
ED scars:
num = intCinputC*\nénter number: “))
‘This wll save the user-entered number as the variable numt
Bile Edt Format Bun Options Windows Help
Tron mininath inport *
print("Select operation.\n")
rint("1.Times by two")
[rint¢"2.Times by Three)
Brint(~3.Square")
Print("4:Poner of”)
choice = input(“\nEnter choice (1/2/3/4):")
runt = int(input("\nnter number: "))
PRED Final, you can now create arange of if statements
to determine what to do with the number and
Utlse the newly created function definitions:
if choice = ‘1’:
print(timestwoCnumt))
elif choice — ‘2:
print(timesthreeCnunt))
elif choice — ‘3?:
print(square(num))
elif choice — ‘4:
riun2 = intCinput(“Enter second number: ))
print(power(num1, nun2))
else:
print(“Invalid input”)
(eat frat Bon Glos xndows wep
BETSER DD Note that forthe last available options the Power
of choice, we've added a second variable, aum2.
This passes a second number through the function definition called
ower, Save and execute the program to see itin action.
(. Create Your Own Modules ¢ Cc )
XNC++ Input/Outputic)
C++ Input/
Output
There's a satisfying feeling when you program
Peele Bare ea ee et ee al
input to produce something that the user can see.
eer eeu en aL)
Eire er AY eeu] l(e)
ean ee
eal elas Ment elec eee RN)
constants and File input and output are all covered
in the Following pages. All of which help you to
Ee eee) kee oon
ee~
C++ Output }
Zz ++ Input/ jutput)
User Interaction
DCR ee ee a ect eT cca ea ch a
basic user interaction is one of the most taught aspects of any language and with it
you're able to do much more than simply greet the user by name.
HELLO, DAVE
You have already used cout, the standard output stream, throughout our code. Now you're going to be using cin, the standard
input stream, to prompta user response.
thing that you wentthe sero inoutntothe
ous? program needs to be stored somewhere in the
autem merry soconberetivedandwsedtreeor oy
input must first be declared as a variable, so it's ready to be used by
RR oc checnedstontccoom on
the user. Star by creating a blank C++ file wth headers.
inputs putinto the integer age and called up in the second cout
‘command, Build and run the code,
Hinclude
‘using namespace std;
int main ()
il TD you're asking a question, you need tostore the
input string; to ask the user thelr name, you
would use!
#include
using namespace std;
‘int main (
Eee The data ype of the variable must also match the
type of input you want From the user. For example,
to.aska user their age, you would use an integer like this: t
#include
using namespace std;
string names
cout << “what is your name
cin >> names
int main ©
cout << “\nllello, “ << nane <<“. I hope you're
int age; well today2\n";
cout << “what is your age: *; i
cin >> ages
cout <<"\nYou are" << age <<" years old.\n"; =* ali) ae bo
} hee women =BETESEM the pxincipal works the same asthe previous code.
‘The users input, their name, is stored in a string,
because it contains multiple characters, and retrieved in the second
using nanespace std;
int main ©
‘int num, mums
cout << “Enter two whole numbers: “;
cin >> uml >> nun;
cout << “you entered “ << numl <<“
num << “\n”;
i
and “ <<
FETISE RD {ikewise, inputted data can be manipulated once
‘you have it stored in a variable. For instance, ask the
user for two numbers and do some maths on them:
include
using nanespace std;
int main ©
float num, num;
cout << “Enter two nunber
cin >> num >> nun2;
Ans
+ << mum <<
cout << num <<
hum + num2 << “\n"
is: “<<
User Interaction ( Cc mm
‘While cin works wel For most input tasks it does
have a limitation. Cin always considers spaces as a
terminator, so it's designed for ust single words not multiple words.
However, getline takes cin as the frst argument and the variable as
Sa}
the second:
#include
using namespace std;
int main ©
string mystr;
cout << “Enter a sentenci
getLine(cin, mystr);
Ans
cout: << “Your sentence is:
characters Long.\n”;
‘<< mystr.size() <<
BTED Build and execute the code, then enter a sentence.
with spaces. when you're done the code reads the
‘numberof characters. f you remove the getline line and replace it
with cin >> mystr and try again, the result displays the number of
characters up to the first space.
Te ERED Cetiine is usually a command that new C++
programmers Forget to include. The terminating
white space is annoying when you cart figure out why your code
isn't working, In short, it's best to use getline(cin, variable) in Future
#include
using namespace std;
int main ©
i
string names
cout. << “Enter your full name: \n”;
getline(cin, nane);
cout << “\nllello, “<< name << “\n
ee~
C++ Output )
Zz ++ Input/ jutput_)
Character Literals
In C++ a literal is an object or variable that once defined remains the same throughout
Lt Keele MnO NE Renee EOL nek Deen Sen A UB OLUA}
been using at the end of a cout statement to signify a new line.
ESCAPE SEQUENCE
When used in something like a cout statement, character literals are also called Escape Sequence Codes. They allow you to
Insert a quote, an alert, new line and much more.
PEPTSEDD create a new C++ file and enter the relevant headers:
include
using namespace std;
int main ©
Finclude
using namespace std:
ant main ()
You've already experienced the \n character literal
placing a new line wherever it's called. The line: cout
-<<"Hello\n" <<"'m a C+#\n" << “Program\n"; outputs three lines
of text, each starting after the last
using namespace std;
int main ©
t
quotes)
'
cout << “Hello, user. This is how to use
‘There's even a character literal that can trigger an
alarm. In Windows 10, i's the notification sound
that chimes when you use a. Try this code, and turn up your sound.
#include
using namespace std;
int main ©
a
cout << “ALARM! \a”;
}
Ries) rs ai Lid «bo
int main ()
er
] cont <<Character Literals cl
A HANDY CHART
There are numerous character literals, or escape sequence codes, to choose from. We therefore thought it would be good for
you to have a handy chart available, for those times when you need to insert a code.
ESCAPE SEQUENCE CODE PANU as
Backlash
Bross
Ag pe a
\ Cruel
acd Cray
\Wroe00.00K Unicode (UTF-16)
UNICODE CHARACTERS (UTF-8)
Unicode characters are symbols or characters that are stand
allplatforms. For example, the copyright symbol, that canbe entered
‘serinteraction. 4 |_ine main
using namespace stds F a
int nain ©
{
cout << “W009”; =
CHARACTER TABLE —
‘Acomplete list of the available Unicode
unicode-table.com/en/. Hover your
mouse over the character to seeits
Unique code to enter in C++.~
C++ Output )
Zz ++ Input/ jutput_)
Defining Constants
(eel e Ma eR AN ol Reel MRED Le cele Cee ea
name suggests their value remains constant throughout the entire code. There are two
Re Ah Cinekensensikeemarese int icerecccee nthe
#DEFINE
‘The pre-processors are instructions to the compiler to pre-process the Information before it goes ahead and compiles the
code. #include isa pre-processor ass #tdefine.
FEED Youcsn use the #define pre-processor to define any [RBTESEEM Note the capitals for defined constants, i's
constants you want in our code. Start by creating 3 considered good programming practise to define all.
new C++ file complete with the usual headers: constants in capitals. Here, the assigned values ae 50, 40 and 60, so
let's call ther up:
#include
using nanespace std #include
ay using nanespace std;
{ define LENGTH 50
#define WIDTH 40
+ #define HEIGHT 60
‘int main Q
Winciuge t
‘tng nameepace sts cout << “Length is: “ << LENGTH << “\n?:
are cout << “Width is: “ << WIDTH << “\n;
cout << “Height is: “ << HEIGHT << “\n?s
Bere Now let’ assume your code has three different
constants: length, width and height. You can define
them with
include
using nanespace std;
‘define LENGTH 50
define WIDTH 40
‘define HEIGHT 60
int main Q >
t
} =
=—_ FETED Build and un the code. Just as expected, it displays
ee the values For each of the constants created. I's
ie fiecinte
using namespace st
define LENGTH 50
define WIDTH 40
define HEIGHT 60
define NEWLINE ‘\n”
int main ©
t
cout << “Length is: “ << LENGTH << NEWLINE;
cout << “Width is: “ << WIDTH << NEWLINE;
cout << “Height is: “ << HEIGHT << NEWLINE;
BTID The code, when built and executed, does exactly the
same as before, using the new constant NEWLINE
toinserta newline inthe cout statement. Incidentally, creating @
newline constant isnt a good idea unless you're makingit smaller
than \n or even the endl command,
PETER Cclining 2 constants 2 good way of initaising your
base values at the start oF your code, You can define
that your game has three lives, or even the value of Plwithout
having to call up the C++ math library:
#include
using nanespace st
define PI 3.14159
int main ©
t
cout << “The value of Pi is: “ << PI << end
BSTEEE DD Axcther method of defining aconstant swith the
const keyword. Use const together with a data type,
variable and value: const type variable = valve, Using Pias an example
#include
Using namespace std;
int main ©
{
const double PI = 3.14159;
cout << “The value of Pi is: “ << PI << endl;
i's worth mentioning that tidefine requires no memory, soif you're
coding toa set amount of memory, stdin is your best bet.
BRT SETERD Const works in much the same way as tdefine,
You can create static integers and even newlines:
#include
Using namespace std;
int main©
i
const int LENGTH = 50;
const int WIDTH = 40;
const char NEWLINE =
int area:
‘rea = LENGTH * WIDTH;
cout << “Area is: “ << area << NEWLINE;Zz C++ Input/Outpu
File Input/Output
The standard iostream library provides C++ coders with the cin and cout input and
Mea aslo lnv aCe AM EU RWC ROM ETCH eee]
(ile Usce- Thole) Go Ne-Ine=| (ler o-1
FSTREAMS
‘There are two main data types within the fstream library that are used to open a file, read From it and write to it, ofstream and
Ifstream. Here's how they work.
Thefetekistoceseanen ite andaing TREE weve nduedonnesindexiettc to
Sua? with the usual headers you need to include the new SueP3 2 to help you understand the process. You created
team header asting called name, tostore the user sinputed name. YOU ao
Created texte caled ame wth the fear nef ard
newt. open nes), askedthe ve forthe name and stored and
then ten the dt the ile
#include
#include
Using namespace stdj
int main Q
‘include
Haclude cestrean>
using namespace std:
‘To readthe contents of afile, and output it to the
snt mass () screen, you need todo things sightyciferenty
Firstyou need to create a string variable to store the file's contents
Re (line byline), then open the il, use getline to read the file ine by
line and output those tiesto the screen. Fnaly, close the fil
BETESE RD Secin by asking a user For their name and writing string Lines
that information toa file. You need the usual string, ‘ifstream newfile C*name, txt”);
tostore the name, and getline to accept the input from the user.
cout << “Contents of the file: “ << endl;
| exits ie;
using namespace std; newfile.close();
‘int main ()
t
string names
ofstream newfiles
newfile open(“name.txt”);,
cout: << “Enter your nane: “<< endl;
getLineCcin, nave);
newfile << name << endl;
newfile.close();
aFETIP the cose above is oreatfor opening afile with one
ortwo lines but what there are multiple lines? Here
‘we openeda text ile of the poem Cimmeria, by Robert E Howard:
string Line;
‘ifstream newfile (“c:\\users\\david\\,
Docunents\\Cinmeria. txt”);
cout << “Cinmeria, by Robert E Howard: \n" <<
endl;
while (getLine(newfile, Line))
cout << Line << end
newfile.close();
Sue doubt see that
we'venduded awhile oop,
wich cverina fw pages
te eeane tha while thre
Br lines tobe read rom the
tet, Cee genes them,
Once athe tines ae read
thecutputis played onthe
screen and he fie closed
BPE DD Youcan also see thatthe location of the text file
Cimmmeria.txt isnt in the same folder asthe C++
program, When we created the first name.tt file, it was writen to
the same Folder where the code was located; this is done by default.
‘To specify another folder, you need to use doubleback slashes, as,
per the character literals/escape sequence code.
Bree estas you might expect, you can write almost
“anything you like toa file, For reading either in
"Notepad or viathe console through the C++ code:
string name;
int age;
ofstream newfile;
newfile-open(“nane.txt”);
cout << “Enter your nane:
getline(cin, name);
newfile << name << endl;
<< endl;
cout << “\nHow old are you: “ << endl;
cin >> ages
newfile << age << endl;
newfile.close();
FRED the code from step 8 differs again, but only where
itcomes to adding the age integer. Notice that
le used cin >> age, instead ofthe previous getine(cin, variable)
The reason for thisisthat the gettine Function handles strings, not
Integers; so when you're using a data type other than string, use
the standard cn,
sere'san exercise: seeifyoucan create codeto
ma? ils write several different elements to a text file. You
canhave ausers name, age, ohone number ete. Maybe even th
nts sal good prac
eee