Chapter 9: Standard C++ strings

Example 9.2, Page no: 214

In [1]:
while True:
    try:
        n = int(raw_input())
        print "n = " , n 
    except:
        break
46
n =  46
22
n =  22
44
n =  44
66
n =  66
88
n =  88
33,

Example 9.4, Page no: 215

In [2]:
king = [] # defines king to be an array 
n=0
while True:
    name = raw_input()
    if len(name) < 1:
        break
    king.append(name)
    n += 1
# now n == the number of names read
for i in range(n):
    print '\t' , i+1 , ". " , king[i] 
Kenneth II (971-995)
Constantine III (995-997)
Kenneth III (997-1005)
Malcolm II (1005-1034)
Duncan I (1034-1040)
Macbeth (1040-1057)
Lulach (1057-1058)
Malcolm III (1058-1093)

	1 .  Kenneth II (971-995)
	2 .  Constantine III (995-997)
	3 .  Kenneth III (997-1005)
	4 .  Malcolm II (1005-1034)
	5 .  Duncan I (1034-1040)
	6 .  Macbeth (1040-1057)
	7 .  Lulach (1057-1058)
	8 .  Malcolm III (1058-1093)

Example 9.6, Page no: 217

In [1]:
'''
Note : you need input.txt in same directory for the program to run without any errors.
'''

infile = open("input.txt","r")
outfile = open("output.txt","w")

for i in infile:
    s = i.title()
    outfile.write(s)

infile.close()
outfile.close()

Example 9.7, Page no: 218

In [2]:
'''Note: You need the files - north.dat, south.dat, combined.dat in the same directory for the program to run without any errors'''

fin1 = open("north.dat","r")
fin2 = open("south.dat","r")
fout = open("combined.dat","w")

file1 = []
file2 = []
for i in fin1:
    try:
        s = i.split(" ")
        for j in s:
            file1.append(int(j))
    except:
        continue
    
for i in fin2:
    try:
        s = i.split(" ")
        for j in s:
            file2.append(int(j))
    except:
        continue


for i in sorted(file1 + file2):
    fout.write(str(i) + " ")

fin1.close()
fin2.close()
fout.close()

Example 9.8, Page no: 219

In [5]:
def print_(oss):
    print 'oss.str() = "' , str(oss) , '"'

s="ABCDEFG"
n=33
x=2.718
l = ''
print_(l)
l += s
print_(l)
l += ( " " + str(n) )
print_(l)
l += ( " " + str(x) )
print_(l)
oss.str() = "  "
oss.str() = " ABCDEFG "
oss.str() = " ABCDEFG 33 "
oss.str() = " ABCDEFG 33 2.718 "

Example 9.9, Page no: 220

In [6]:
def print_(iss,s='',n=0,x=0.0):
    print 's = "' , s , '", n = ' , n , ", x = " , x, ', iss.str() = "' \
                            , iss , '"' 

s=""
n=0
x=0.0
l = ''
iss = "ABCDEFG 44 3.14"
print_(iss)
s = "ABCDEFG"
print_(iss,s)
n = 44
print_(iss,s,n)
x = 3.14
print_(iss,s,n,x)
s = "  ", n =  0 , x =  0.0 , iss.str() = " ABCDEFG 44 3.14 "
s = " ABCDEFG ", n =  0 , x =  0.0 , iss.str() = " ABCDEFG 44 3.14 "
s = " ABCDEFG ", n =  44 , x =  0.0 , iss.str() = " ABCDEFG 44 3.14 "
s = " ABCDEFG ", n =  44 , x =  3.14 , iss.str() = " ABCDEFG 44 3.14 "