computer programming- lecture 5
DESCRIPTION
C-StringsTRANSCRIPT
1Computer Programming I
Lecture 5C-Strings
2Computer Programming I
Outline
C-strings Functions for C-strings C-strings input C-strings output C-strings to numbers
3Computer Programming I
Problems
How do I store the names of students? How do I specify filenames? How to I manipulate text?
4Computer Programming I
String Taxonomy
5Computer Programming I
An Array Type for Strings C-strings can be used to represent strings of
characters C-strings are stored as arrays of characters C-strings use the null character '\0' to end a string
The Null character is a single character
To declare a C-string variable, declare an array of characters:
char s[11];
6Computer Programming I
Arrays A series of elements (variables) of the same type Placed consecutively in memory Can be individually referenced by adding an index to
a unique name Example, an array to contain 5 integer values of type
int called item:int item[5];
item0 1 2 3 4
int
7Computer Programming I
An Array Type for Strings C-strings can be used to represent strings of
characters C-strings are stored as arrays of characters C-strings use the null character '\0' to end a string
The Null character is a single character
To declare a C-string variable, declare an array of characters:
char s[11];
8Computer Programming I
C-string Details Declaring a C-string as char s[10] creates
space for only nine characters The null character terminator requires one space
A C-string variable does not need a size variable The null character(‘\0’) immediately follows the last
character of the string
Example:
??\0!moMiHs[9]s[8]s[7]s[6]s[5]s[4]s[3]s[2]s[1]s[0]
9Computer Programming I
C-string Declaration
To declare a C-string variable, use the syntax:
char Array_name[ Maximum_C_String_Size + 1];
+ 1 reserves the additional character needed by '\0'
10Computer Programming I
Initializing a C-string To initialize a C-string during declaration:
char my_message[20] = "Hi there."; The null character '\0' is added for you
Another alternative: char short_string[ ] = "abc"; but not this: char short_string[ ] = {'a', 'b', 'c'};
11Computer Programming I
C-string error
This attempt to initialize a C-string does not cause the ‘\0’ to be inserted in the array char short_string[ ] = {'a', 'b', 'c'};
12Computer Programming I
C-style string
char name[10]={'H','e','l','l','o','\0'};
char name[10]="Hello";
is equivalent
The declaration:A C-style string in C++ is basically an array of characters, terminated by a null character ('\0')
H e l l o \0
(the size of the array is 10, the length of the string is 5)
When we count the length of the string, we do not count the terminating null character.
13Computer Programming I
char name[]={'H','e','l','l','o','\0'};
char name[]="Hello";
is equivalent
The declaration:
If the size of the array is not specified, then the array size would be equal to the length of the string plus 1
H e l l o \0
(the size of the array is 6, the length of the string is 5)
14Computer Programming I
char name[6]={'H','\0'};
char name[6]="H";
is equivalent
The declaration:
H \0
(the size of the array is 6, But the length of the string is 1)
char name[]={'H','\0'};
char name[]="H";
is equivalent
The declaration:
H \0
(the size of the array is 2, But the length of the string is 1)
15Computer Programming I
char name[]={'\0'};
char name[]="";
is equivalent
The declaration:
\0
(the size of the array is 1, the length of the string is 0)
Null string(empty string)
char name[6]={'\0'};
char name[6]="";
is equivalent
The declaration:
\0
(the size of the array is 1, the length of the string is 0)
16Computer Programming I
char name='H';
char name[]="H";
is NOT equivalent
The declaration:
H \0
(the size of the array is 2, the length of the string is 1)
H
(this is not an array nor a string,it is simply a character)
17Computer Programming I
char name[11]="John Connor";
Note: If you just want to have an array of characters, then this MAY be ok.
J o h n C o n n o r
Warning: if you want to use this as string with the C’s standard string manipulation library, then you may run into problems because the string is not null terminated.
18Computer Programming I
Assignment With C-strings
This statement is illegal:
a_string = "Hello"; This is an assignment statement, not an
initialization The assignment operator does not work
with C-strings
19Computer Programming I
Assignment of C-strings A common method to assign a value to a
C-string variable is to use strcpy, defined in the cstring library Example: #include <cstring>
… char a_string[ 11];
strcpy (a_string, "Hello");
Places "Hello" followed by the null character in a_string
20Computer Programming I
#include <iostream>#include <cstring>using namespace std;int main() { char source[] = "Judgement Day"; char dest[] = "Rise of the Machine"; strncpy(dest,source); cout << "source = " << source << endl; cout << " dest = " << dest << endl;}
source = Judgement Day dest = Judgement Day
strcpy()
Copy one string into another. Copy string source to dest, stopping after the terminating null character has been moved.
WARNING : Make sure the destination string has enough allocated array space to store the new string. The compiler will not warn you about this, you MAY probably corrupted some part of the computer memory if your destination array of characters is not big enough to store the new string. This is DANGEROUS, so be careful !!!
21Computer Programming I
int main(){ char source[] = "Judgement Day"; char dest[] = "Rise of the Machine";
dest = source; . . .}
WARNING : You cannot assign one string to another just as you can't assign one array to another !!!
The compiler will give an error.
22Computer Programming I
int main() { char dest[20]; dest = "Judgement Day";}
WARNING : You cannot assign one string to another just as you can't assign one array to another !!! Use strcpy() function instead.
int main() { char dest[20] = "Judgement Day";}
int main() { char dest[20]; strcpy(dest,"Judgement Day");}
This is an initialization, it is valid.
This is an assignment, it is NOT valid. Use strcpy to assign a c-string
to another c-string
23Computer Programming I
A Problem With strcpy
strcpy can create problems if not used carefully strcpy does not check the declared length
of the first argument
It is possible for strcpy to write characters beyond the declared size of the array
24Computer Programming I
A Solution for strcpy Many versions of C++ have a safer version of
strcpy named strncpy strncpy uses a third argument representing the
maximum number of characters to copy Example: char another_string[10];
strncpy(another_string, a_string_variable, 9);
This code copies up to 9 characters into another_string, leaving one space for '\0'
25Computer Programming I
== Alternative for C-strings The = = operator does not work as expected with
C-strings The predefined function strcmp is used to compare C-
string variables Example: #include <cstring>
… if (strcmp(c_string1, c_string2)) cout << "Strings are not the same."; else cout << "String are the same.";
26Computer Programming I
strcmp's logic strcmp compares the numeric codes of
elements in the C-strings a character at a time If the two C-strings are the same, strcmp returns 0
0 is interpreted as false
As soon as the characters do not match strcmp returns a negative value if the numeric code in
the first parameter is less strcmp returns a positive value if the numeric code in the
second parameter is less Non-zero values are interpreted as true
27Computer Programming I
#include <iostream>#include <cstring>using namespace std;int main() { char string1[] = "Hello"; char string2[] = "Hello World"; char string3[] = "Hello World"; char string4[] = "Aloha"; int n;
strcmp()Compare one string to another starting with the first character in each string and continuing with subsequent characters until the corresponding characters differ or until the end of the strings is reached.
n = strcmp(string1, string2); cout << string1 << "\t\t" << string2 << "\t==> " << n << endl;
n = strcmp(string2, string3); cout << string2 << '\t' << string3 << "\t==> " << n << endl;
n = strcmp(string3, string4); cout << string3 << '\t' << string4 << "\t\t==> " << n << endl;}
Hello Hello World ==> -1
Hello World Hello World ==> 0
Hello World Aloha ==> 1
28Computer Programming I
#include <iostream>#include <cstring>using namespace std;int main() { char string1[] = "Hello"; char string2[] = "Hello";
if ( string1==string2 ) cout << "Same"; else cout << "Different"; }
WARNING : You should not use the logical comparison to compare whether two C-strings are identical.
The compiler will NOT give you any compile-time errors nor warning, but you will not be getting the results you thought you would get.
Different
output:
29Computer Programming I
Use strcmp() function instead for string comparison.
Same
output:
#include <iostream>#include <cstring>using namespace std;int main() { char string1[] = "Hello"; char string2[] = "Hello";
if (strcmp(string1,string2)==0 ) cout << "Same"; else cout << "Different"; }
30Computer Programming I
More C-string Functions The cstring library includes other functions
strlen returns the number of characters in a string int x = strlen( a_string);
strcat concatenates two C-strings The second argument is added to the end of the first The result is placed in the first argument Example:
char string_var[20] = "The rain"; strcat(string_var, "in Spain");
Now string_var contains "The rainin Spain"
31Computer Programming I
The strncat Function
strncat is a safer version of strcat A third parameter specifies a limit for the
number of characters to concatenate Example:
char string_var[20] = "The rain"; strncat(string_var, "in Spain", 11);
32Computer Programming I
#include <iostream>#include <cstring>using namespace std;int main() { char dest[30] = "Rise of "; char source[] = "The Machine";
strcat( dest, source ); cout << " dest = " << dest << endl; cout << "source = " << source << endl;}
dest = Rise of The Machinesource = The Machine
strcat()
Appends one string to another. strcat() appends a copy of source to the end of dest. The length of the resulting string is strlen(dest) + strlen(source).
WARNING : Make sure the destination string has enough allocated array space to store the new string. The compiler will not warn you about this, you MAY probably corrupted some part of the computer memory if your destination array of characters is not big enough to store the new string. This is DANGEROUS, so be careful !!!
33Computer Programming I
char s1[12]="Hello";char s2[]="World";
H e l l o \0
s1W o r l d \0
s2
H e l l o W o r l d \0
s1W o r l d \0
s2
strcat(s1,s2);
34Computer Programming I
C-String functions in C's Standard Library
Must #include <cstring> Most common functions:
strlen() – get the length of the string without counting the terminating null character.
strncpy() - copy one string to another string strcmp() - compare two string strncat() - concatenates / join two string
35Computer Programming I
C-string Output
C-strings can be output with the insertion operator Example: char news[ ] = "C-strings";
cout << news << " Wow." << endl;
36Computer Programming I
C-string Input The extraction operator >> can fill a C-
string Whitespace ends reading of data Example: char a[80], b[80];
cout << "Enter input: " << endl; cin >> a >> b; cout << a << b << "End of Output";could produce: Enter input: Do be do to you! DobeEnd of Output
37Computer Programming I
Simple C-String Input and Output
#include <cstring>#include <iostream>using namespace std;
int main(){ char name[10]; cout << "Name => ";
cin >> name; cout << "Name is [" << name << "]" << endl;
cout << "Name length is " << strlen(name);}
Consider this program :Declaring name to be an array of characters
Standard function to return the length of the string
must #include this for using strlen() function
To treat the array of characters as C-string, we just use the name of the array when dealing with I/O stream.
38Computer Programming I
Name => helloName is [hello]Name length is 5
#include <cstring>#include <iostream>using namespace std;int main() { char name[10]; cout << "Name => "; cin >> name; cout << "Name is [“ << name << "]\n"; cout << "Name length is “ << strlen(name);}
Sample run 1:
[remark: no problem]
Name => Hello thereName is [Hello]Name length is 5
Sample run 2:
[remark: the cin will stop scanning after the space character is encountered.
39Computer Programming I
Reading an Entire Line
Predefined member function getline can read an entire line, including spaces getline is a member of all input streams getline has two arguments
The first is a C-string variable to receive input The second is an integer, usually the size of the
first argument specifying the maximum number of elements in the first argument getline is allowed to fill
40Computer Programming I
Using getline The following code is used to read an entire
lineincluding spaces into a single C-string variable char a[80];
cout << "Enter input:\n";cin.getline(a, 80);cout << a << End Of Output\n";
and could produce: Enter some input: Do be do to you! Do be do to you!End of Output
41Computer Programming I
getline syntax Syntax for using getline is
cin.getline(String_Var, Max_Characters + 1);
cin can be replaced by any input stream Max_Characters + 1 reserves one element for the null
character
42Computer Programming I
#include <cstring>#include <iostream>using namespace std;int main() { char name[10]; cout << "Name => "; cin >> name; cout << "Name is [“ << name << "]\n"; cout << “The Length: “ << strlen(name);}
Name => HelloThereHowAreYouName is [HelloThereHowAreYou]Name length is 19
Sample run:
Warning: we have allocated only 10 characters to store the string, where has all the extra characters gone to?
Answer : We have probably corrupted some part of the memory, this is DANGEROUS, so be careful !!!]
More C-String Input and Outputconsider:
43Computer Programming I
#include <iostream>using namespace std;int main () { char name[20]; cin.get(name,10); cout << "[" << name << "]";}
alibabamuthu[alibabamu]
ali[ali]
sample run 2:
sample run 1:
ali baba muthu[ali baba ]
sample run 3:
user press enter, stop
reading because '\n' is
the default delimiter.
9 characters read, including 2 tab '\t' characters.
Input functions : character array input usingInput functions : character array input using cin.get(...)
only 9 character read, NOT 10.
Specifies the maximum number of bytes to be filled into the character array, in the case here, 10 character will be filled, meaning 9 characters will be read (NOT 10) from input stream, the 10th character is null character ("\0').
44Computer Programming I
#include <iostream>using namespace std;int main () { char name[20]; cin.get(name,10,'z'); cout << "[" << name << "]";}
alibabamuthu[alibabamu]
alibabamuthu[alibaba]
sample run 2:
sample run 1:
afizuddin[afi]
sample run 3:
user press enter, '\n' is read as valid input since '\n' is NOT the delimiter.
the character 'z' is used as delimiter the delimiter
(which is 'z' in this case) is encounter, thus stop reading
same as before
45Computer Programming I
#include <iostream>using namespace std;int main () { char name[20]; cin >> name; cout << "[" << name << "]";}
ab cde[ab]
output:
Remember : cin.get(...) read whitespaces as valid input character unless the whitespace is delimiter
#include <iostream>using namespace std;int main () { char name[20]; cin.get(name,10); cout << "[" << name << "]";}
output:
ab cde[ab cde]
46Computer Programming I
#include <iostream>using namespace std;int main () { char name1[10],name2[10],name3[10]; cin.getline(name1,10); cout << "[" << name1 << "]\n"; cin.getline(name2,10); cout << "[" << name2 << "]\n"; cin.getline(name3,10); cout << "[" << name3 << "]\n";}
sample run 1:
Input functions : overcome delimiter problem using cin.getline(...)
mary[mary]peter[peter]john[john]
This solved the delimiter problem!!
47Computer Programming I
#include <iostream>using namespace std;int main () { char name1[10],name2[10],name3[10]; cin.getline(name1,10,'p'); cout << "[" << name1 << "]\n"; cin.getline(name2,10,'j'); cout << "[" << name2 << "]\n"; cin.getline(name3,10,'a'); cout << "[" << name3 << "]\n"; }
sample run 1:marypeter[mary]panjohn[eterpan]carl[ohnc]
Why?
48Computer Programming I
Assigning Characters Into C-Strings#include <cstring>#include <iostream>using namespace std;
int main() { char str[11]; str[0] = 'H'; str[1] = 'I'; str[2] = '\0'; cout << str << endl;
for (int i=0; i<=9; i++) str[i] = 'A' + i; str[i] = '\0'; cout << str << endl;
str[5] = '\0'; for (int i=0; i<=10; i++) cout << "[" << static_cast<int>( str[i] ) << "]"; cout << endl; cout << str << endl;
str[5] = 'A'; cout << str << endl; system("pause");}
HIABCDEFGHIJ[65][66][67][68][69][0][71][72][73][74][0]ABCDEABCDEAGHIJ
Strings are treated just like an array of character values here. The null character is used to indicate the end of the string when processed by the standard library such as puts() function.
output:
49Computer Programming I
WARNING : You can not use arithmetic addition in order to concatenate two C-string. The compiler will give you compile-time errors.
#include <iostream>#include <cstring>using namespace std;int main() { char dest[30] = "Rise of "; char source[] = "The Machine";
dest = dest + source; cout << " dest = " << dest << endl; cout << "source = " << source << endl;}
Computer Programming I 50
Array of C-Strings
char actor[30];
The declaration:declares one string of which the maximum length is 29.A c-string is an one-dimensional array of characters.
How do I declared an array of c-strings?
char actor[5][30];
one solution:This declare an array of 5 strings, of which the maximum length of the string is 30.That means, an array of strings is actually a two-dimensional array of characters.
Computer Programming I 51
char actor[4][10] = { "Arnold", "Nick", "Claire", "Kristanna" };
A r n o l d \0
N i c k \0
C l a i r e \0
K r i s t a n n a \0
actor[0]
actor[1]
actor[2]
actor[3]
0 1 2 3 4 5 6 7 8 9
Computer Programming I 52
#include <iostream>#include <cstring>using namespace std;int main() { char actor[4][30] = { "Sylvester Stallon", "Nick Stahl", "Claire Danes" }; char anotherActor[30] = "Arnold Schwarzenegger";
cout << anotherActor << endl; cout << actor[0] << endl;
strcpy ( actor[0], anotherActor ); strcpy ( actor[3], "Kristanna Loken" );
for (int i=0; i<=3; i++) cout << i << " " << actor[i] << endl;} Arnold Schwarzenegger
Sylvester Stallon0 Arnold Schwarzenegger1 Nick Stahl2 Claire Danes3 Kristanna Loken
Example:
53Computer Programming I
C-String to Numbers "1234" is a string of characters 1234 is a number When doing numeric input, it is useful to read
input as a string of characters, then convert the string to a number Reading money may involve a dollar sign Reading percentages may involve a percent sign
54Computer Programming I
C-strings to Integers To read an integer as characters
Read input as characters into a C-string, removing unwanted characters
Use the predefined function atoi to convert the C-string to an int value
Example: atoi("1234") returns the integer 1234 atoi("#123") returns 0 because # is not a digit
55Computer Programming I
C-string to long
Larger integers can be converted using the predefined function atol
atol returns a value of type long
56Computer Programming I
C-string to double
C-strings can be converted to type double using the predefined function atof
atof returns a value of type double Example: atof("9.99") returns 9.99
atof("$9.99") returns 0.0 because the $ is not a digit
57Computer Programming I
Library cstdlib The conversion functions
atoi atol
atofare found in the library cstdlib
To use the functions use the include directive
#include <cstdlib>
58Computer Programming I
#include <iostream>#include <cstring>using namespace std;int main() { char str1[] = "1234"; char str2[] = "0123"; char str3[] = " 123"; char str4[] = "$123"; char str5[] = "12.34"; int n1,n2,n3,n4,n5; double d1,d2,d3,d4,d5; long l1,l2,l3,l4,l5; n1 = atoi(str1); n2 = atoi(str2); n3 = atoi(str3); n4 = atoi(str4); n5 = atoi(str5); d1 = atof(str1); d2 = atof(str2); d3 = atof(str3); d4 = atof(str4); d5 = atof(str5); l1 = atol(str1); l2 = atol(str2); l3 = atol(str3); l4 = atol(str4); l5 = atol(str5); cout << n1 << " " << n2 << " " << n3 << " " << n4 << " " << n5 << endl; cout << d1 << " " << d2 << " " << d3 << " " << d4 << " " << d5 << endl; cout << l1 << " " << l2 << " " << l3 << " " << l4 << " " << l5 << endl;}
1234 123 123 0 121234 123 123 0 12.341234 123 123 0 12
output:
C-String conversion to numbers
59Computer Programming I
Predefined Functions
toupper(char_exp) – convert lowercase character to uppercase
tolower(char_exp) – convert uppercase character to lowercase
isupper(char_exp) – tests if character is an uppercase letter
islower(char_exp) – tests if character is a lowercase letter
isalpha(char_exp) – tests if character is alphanumeric
isdigit(char_exp) – tests if character is digit
isspace(char_exp) – tests if character is white-space character
60Computer Programming I
Predefined Functions (cont.)
atoi(str_exp) ingr1 = atoi(str1); Parses string interpreting its content as a number and returns an int value
atof (str_exp) dbl1 = atof(str1); Parses string interpreting its content as a floating point number and returns a value of type double
atol (str_exp) lng1 = atol(str1); Parses string interpreting its content as a number and returns a long value.
61Computer Programming I
The End