SlideShare a Scribd company logo
1 of 61
Lecture 5
              C-Strings




Computer Programming I    1
Outline
   C-strings
   Functions for C-strings
   C-strings input
   C-strings output
   C-strings to numbers




    Computer Programming I     2
Problems
 How do I store the names of students?
 How do I specify filenames?
 How to I manipulate text?




    Computer Programming I                3
String Taxonomy




Computer Programming I     4
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];




    Computer Programming I                                     5
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];
              0       1       2       3       4

    item
             int




    Computer Programming I                                  6
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];




    Computer Programming I                                     7
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:
                  s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]

                  H i            M o m !             0    ?    ?

    Computer Programming I                                            8
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'




    Computer Programming I                         9
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'};



    Computer Programming I                          10
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'};




    Computer Programming I                       11
C-style string                         A C-style string in C++ is
The declaration:                        basically an array of
                                        characters, terminated by a
char name[10]="Hello";
                                        null character ('0')

        is equivalent                            When we count the
                                                 length of the string,
 char name[10]={'H','e','l','l','o','0'};       we do not count the
                                                 terminating null
                                                 character.


             H     e   l   l   o   0

     (the size of the array is 10, the length of the string is 5)



    Computer Programming I                                          12
The declaration:

                                      If the size of the array is not
char name[]="Hello";                  specified, then the array
                                      size would be equal to the
     is equivalent                    length of the string plus 1

 char name[]={'H','e','l','l','o','0'};




           H   e     l   l   o   0

   (the size of the array is 6, the length of the string is 5)



   Computer Programming I                                        13
The declaration:                        The declaration:


  char name[6]="H";                       char name[]="H";



               is equivalent                           is equivalent



char name[6]={'H','0'};                char name[]={'H','0'};



   H     0                                H     0
   (the size of the array is 6,            (the size of the array is 2,
   But the length of the string is 1)      But the length of the string is 1)




  Computer Programming I                                               14
Null string
     The declaration:           (empty string)        The declaration:


  char name[6]="";                                 char name[]="";



               is equivalent                                    is equivalent



char name[6]={'0'};                             char name[]={'0'};



   0                                               0
   (the size of the array is 1,                     (the size of the array is 1,
   the length of the string is 0)                   the length of the string is 0)




  Computer Programming I                                                        15
The declaration:


  char name[]="H";
                                     H    0
                                     (the size of the array is 2,
             is   NOT   equivalent   the length of the string is 1)



char name='H';                       H
                                     (this is not an array nor a string,
                                     it is simply a character)




  Computer Programming I                                                   16
char name[11]="John Connor";



                     J   o     h   n   C   o   n   n   o   r



Note: If you just want to have an array of characters,
then this MAY be ok.

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.


 Computer Programming I                                        17
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




    Computer Programming I                       18
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



    Computer Programming I                               19
#include <iostream>
#include <cstring>                                  strcpy()
using namespace std;
int main() {
  char source[] = "Judgement Day";                   Copy one string into
  char   dest[] = "Rise of the Machine";             another. Copy string
  strncpy(dest,source);
                                                     source to dest,
  cout << "source = " << source << endl;
  cout << " dest = " << dest    << endl;             stopping after the
}                                                    terminating null
                                                     character has been
                                                     moved.
           source = Judgement Day
             dest = Judgement Day


  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 !!!
    Computer Programming I                                              20
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.




   Computer Programming I                                       21
int main() {                             This is an initialization, it
  char dest[20] = "Judgement Day";
}
                                         is valid.


int main() {                            int main() {
  char   dest[20];                       char   dest[20];
  dest = "Judgement Day";                strcpy(dest,"Judgement Day");
}                                       }
  This is an assignment, it is
  NOT valid.                             Use strcpy to assign a c-string
                                         to another c-string


  WARNING : You cannot assign one string to another just as you
  can't assign one array to another !!! Use strcpy() function instead.



  Computer Programming I                                                 22
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




    Computer Programming I                             23
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'

    Computer Programming I                              24
== 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.";




    Computer Programming I                                        25
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


    Computer Programming I                                             26
#include <iostream>
#include <cstring>                                    strcmp()
using namespace std;                     Compare one string to another starting
int main() {                             with the first character in each string and
 char string1[] = "Hello";               continuing with subsequent characters
 char string2[] = "Hello World";         until the corresponding characters differ
 char string3[] = "Hello World";         or until the end of the strings is reached.
 char string4[] = "Aloha";
 int n;

    n = strcmp(string1, string2);
    cout << string1 << "tt" << string2 << "t==> " << n << endl;
                                          Hello           Hello World   ==> -1
    n = strcmp(string2, string3);
    cout << string2 << 't' << string3 << "t==> " << n << endl;
                                          Hello World     Hello World   ==> 0
    n = strcmp(string3, string4);
    cout << string3 << 't' << string4 << "tt==> " << n << endl;
}
                                          Hello World     Aloha         ==> 1
           Computer Programming I                                                27
#include <iostream>
  #include <cstring>
  using namespace std;
  int main() {
   char string1[] = "Hello";
   char string2[] = "Hello";

      if ( string1==string2 )
         cout << "Same";                           output:
         else                                  Different
             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.


   Computer Programming I                                         28
#include <iostream>
  #include <cstring>
  using namespace std;
  int main() {
   char string1[] = "Hello";
   char string2[] = "Hello";

      if (strcmp(string1,string2)==0 )
         cout << "Same";                               output:
         else                                   Same
             cout << "Different";
  }



Use strcmp() function instead for string comparison.




   Computer Programming I                                        29
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"




    Computer Programming I                                       30
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);




    Computer Programming I                           31
#include <iostream>
#include <cstring>
                                                      strcat()
using namespace std;
int main() {
 char dest[30] = "Rise of ";                     Appends one string to
 char source[] = "The Machine";                  another. strcat()
                                                 appends a copy of
 strcat( dest, source );                         source to the end of
 cout << " dest = " << dest << endl;             dest. The length of
 cout << "source = " << source << endl;          the resulting string is
}
                                                 strlen(dest) +
               dest = Rise of The Machine        strlen(source).
             source = The Machine

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 !!!


    Computer Programming I                                        32
char s1[12]="Hello";
                                   char s2[]="World";


s1                                                       s2
 H   e    l   l   o   0                                  W   o   r   l   d   0




                                        strcat(s1,s2);



s1                                                       s2
H    e    l   l   o   W    o   r    l     d   0          W   o   r   l   d   0




         Computer Programming I                                               33
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




      Computer Programming I                                   34
C-string Output
   C-strings can be output with the
    insertion operator
      Example:         char news[ ] = "C-strings";
                        cout << news << " Wow."
                              << endl;




    Computer Programming I                            35
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


    Computer Programming I                                  36
Simple C-String Input and Output
                                                 must #include this for using
Consider this program :                          strlen() function

 #include <cstring>                  Declaring name to be an
 #include <iostream>                 array of characters
 using namespace std;

 int main()
 {                               To treat the array of characters as C-
   char name[10];                string, we just use the name of the
   cout << "Name => ";
                                 array when dealing with I/O stream.
  cin >> name;

  cout << "Name is [" << name << "]" << endl;

  cout << "Name length is " <<   strlen(name);
 }
                                             Standard function to return the
                                             length of the string


     Computer Programming I                                               37
#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:                  Sample run 2:
                               Name => Hello there
Name => hello
                               Name is [Hello]
Name is [hello]
                               Name length is 5
Name length is 5
                               [remark: the cin will stop
[remark: no problem]           scanning after the space
                               character is encountered.


      Computer Programming I                                38
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



    Computer Programming I                                    39
Using getline
   The following code is used to read an entire
    line
    including spaces into a single C-string
    variable
               char a[80];
                cout << "Enter input:n";
                cin.getline(a, 80);
                cout << a << End Of Outputn";
         and could produce:
                Enter some input:
                 Do be do to you!
                 Do be do to you!End of Output


    Computer Programming I                         40
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




      Computer Programming I                                 41
More C-String Input and Output
                                       Sample run:
consider:
                                      Name => HelloThereHowAreYou
#include <cstring>                    Name is [HelloThereHowAreYou]
#include <iostream>                   Name length is 19
using namespace std;
int main() {
      char name[10];
      cout << "Name => ";
      cin >> name;
      cout << "Name is [“ << name << "]n";
      cout << “The Length: “ << strlen(name);
}

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 !!!]
       Computer Programming I                                        42
Input functions : character array input using cin.get(...)

#include <iostream>                            sample run 1:       only 9
using namespace std;                                               character
                                               alibabamuthu
int main () {                                  [alibabamu]         read, NOT 10.
   char name[20];                                                         user press
   cin.get(name,10);                           sample run 2:              enter, stop
                                                  ali                       reading
   cout << "[" << name << "]";                                           because 'n' is
                                                  [ali]
}                                                                         the default
                                                                           delimiter.

Specifies the maximum number of
bytes to be filled into the character                            9 characters read,
array, in the case here, 10 character                            including 2 tab 't'
                                                                 characters.
will be filled, meaning 9 characters    sample run 3:
will be read (NOT 10) from input
                                               ali        baba       muthu
stream, the 10th character is null
                                               [ali       baba       ]
character ("0').


        Computer Programming I                                                   43
#include <iostream>                sample run 1:
using namespace std;                                  same as
                                   alibabamuthu       before
int main () {                      [alibabamu]
   char name[20];
   cin.get(name,10,'z');              sample run 2:        user press
                                                            enter, 'n'
   cout << "[" << name << "]";        ali
                                                           is read as
                                      baba
}                                                          valid input
                                      muthu
                                                           since 'n' is
                                      [ali
                                                            NOT the
                                      baba
                                                            delimiter.
                                      ]
the character 'z' is used
     as delimiter                                   the delimiter
                                 sample run 3:    (which is 'z' in this
                                 afizuddin       case) is encounter,
                                 [afi]            thus stop reading




        Computer Programming I                                      44
#include <iostream>
using namespace std;
int main () {                                    output:
   char name[20];                                 ab cde
   cin >> name;                                   [ab]
   cout << "[" << name << "]";
}

#include <iostream>
using namespace std;                             output:
int main () {
                                                  ab cde
   char name[20];                                 [ab cde]
   cin.get(name,10);
   cout << "[" << name << "]";
}

                      Remember : cin.get(...) read whitespaces as
                    valid input character unless the whitespace is delimiter



     Computer Programming I                                            45
Input functions : overcome delimiter problem using cin.getline(...)

#include <iostream>
using namespace std;                            sample run 1:
int main () {                                    mary
                                                 [mary]       This
  char name1[10],name2[10],name3[10];            peter     solved the
  cin.getline(name1,10);                         [peter]    delimiter
                                                 john      problem!!
  cout << "[" << name1 << "]n";                 [john]
  cin.getline(name2,10);
  cout << "[" << name2 << "]n";
  cin.getline(name3,10);
  cout << "[" << name3 << "]n";
}




      Computer Programming I                                    46
#include <iostream>
using namespace std;                    sample run 1:
int main () {                            marypeter
                                         [mary]
  char name1[10],name2[10],name3[10];    pan
  cin.getline(name1,10,'p');             john
                                         [eter
  cout << "[" << name1 << "]n";         pan
  cin.getline(name2,10,'j');             ]
  cout << "[" << name2 << "]n";         carl
                                         [ohn
  cin.getline(name3,10,'a');             c]
  cout << "[" << name3 << "]n";
}                                            Why?




     Computer Programming I                             47
Assigning Characters Into C-Strings
#include <cstring>
#include <iostream>                                    Strings are treated just
using namespace std;
                                                       like an array of
int main() {                                           character values here.
 char str[11];                                         The null character is
 str[0] = 'H'; str[1] = 'I'; str[2] = '0';            used to indicate the
 cout << str << endl;
                                                       end of the string when
 for (int i=0; i<=9; i++) str[i] = 'A' + i;            processed by the
 str[i] = '0';                                        standard library such
 cout << str << endl;
                                                       as puts() function.
 str[5] = '0';
 for (int i=0; i<=10; i++)
   cout << "[" << static_cast<int>( str[i] ) << "]";
 cout << endl;                                             output:
 cout << str << endl;
                           HI
                           ABCDEFGHIJ
 str[5] = 'A';
 cout << str << endl;      [65][66][67][68][69][0][71][72][73][74][0]
 system("pause");          ABCDE
}                          ABCDEAGHIJ

       Computer Programming I                                               48
#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;
}



    WARNING : You can not use arithmetic addition in order to
    concatenate two C-string. The compiler will give you compile-time
    errors.




       Computer Programming I                                           49
Array of C-Strings
 The declaration:
                     declares one string of which the maximum
                     length is 29.
 char actor[30];
                     A c-string is an one-dimensional array of
                     characters.

        How do I declared an array of c-strings?

  one solution:
                     This declare an array of 5 strings, of which
char actor[5][30];
                     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                                       50
char actor[4][10] = { "Arnold",
                       "Nick",
                       "Claire",
                       "Kristanna" };




                            0   1   2   3   4    5   6    7   8   9
                 actor[0]   A   r   n   o   l    d   0
                 actor[1]   N   i   c   k   0
                 actor[2]   C   l   a   i   r    e   0
                 actor[3]   K   r   i   s   t    a   n    n   a   0




  Computer Programming I                                               51
Example:
#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 Stallon
                                                    0 Arnold Schwarzenegger
                                                    1 Nick Stahl
                                                    2 Claire Danes
      Computer Programming I                        3 Kristanna Loken     52
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




    Computer Programming I                              53
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




    Computer Programming I                                      54
C-string to long

   Larger integers can be converted using
    the predefined function atol

      atol returns a value of type long




    Computer Programming I                   55
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




    Computer Programming I                   56
Library cstdlib
 The conversion functions
                      atoi
                      atol
                      atof
  are found in the library cstdlib
 To use the functions use the include
  directive

                   #include <cstdlib>

    Computer Programming I               57
C-String conversion to numbers
 #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 12
                            output:     1234 123 123 0 12.34
                                        1234 123 123 0 12




      Computer Programming I                                                 58
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



   Computer Programming I                                          59
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.


   Computer Programming I                                       60
The End




Computer Programming I     61

More Related Content

What's hot (20)

Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
Stl Containers
Stl ContainersStl Containers
Stl Containers
 
Theory of programming
Theory of programmingTheory of programming
Theory of programming
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming Python programming | Fundamentals of Python programming
Python programming | Fundamentals of Python programming
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Function
FunctionFunction
Function
 
Strings in C language
Strings in C languageStrings in C language
Strings in C language
 
C tutorial
C tutorialC tutorial
C tutorial
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Two dimensional array
Two dimensional arrayTwo dimensional array
Two dimensional array
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Structure in c
Structure in cStructure in c
Structure in c
 
Enums in c
Enums in cEnums in c
Enums in c
 

Viewers also liked

Viewers also liked (7)

Computer Programming- Lecture 10
Computer Programming- Lecture 10Computer Programming- Lecture 10
Computer Programming- Lecture 10
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
Computer Programming- Lecture 11
Computer Programming- Lecture 11Computer Programming- Lecture 11
Computer Programming- Lecture 11
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
Computer Programming- Lecture 8
Computer Programming- Lecture 8Computer Programming- Lecture 8
Computer Programming- Lecture 8
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 

Similar to Computer Programming- Lecture 5

Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01Md. Ashikur Rahman
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxJStalinAsstProfessor
 
Character array (strings)
Character array (strings)Character array (strings)
Character array (strings)sangrampatil81
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptxJawadTanvir
 
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptxAbhimanyuChaure
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programmingmikeymanjiro2090
 
C Programming Strings.docx
C Programming Strings.docxC Programming Strings.docx
C Programming Strings.docx8759000398
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTSasideepa
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTSasideepa
 

Similar to Computer Programming- Lecture 5 (20)

String in c
String in cString in c
String in c
 
Cse115 lecture14strings part01
Cse115 lecture14strings part01Cse115 lecture14strings part01
Cse115 lecture14strings part01
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
fundamentals of c programming_String.pptx
fundamentals of c programming_String.pptxfundamentals of c programming_String.pptx
fundamentals of c programming_String.pptx
 
14 strings
14 strings14 strings
14 strings
 
COm1407: Character & Strings
COm1407: Character & StringsCOm1407: Character & Strings
COm1407: Character & Strings
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Character array (strings)
Character array (strings)Character array (strings)
Character array (strings)
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptxINDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
INDIAN INSTITUTE OF TECHNOLOGY KANPURESC 111M Lec13.pptx
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
C Programming Strings.docx
C Programming Strings.docxC Programming Strings.docx
C Programming Strings.docx
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
 
CP-STRING (1).ppt
CP-STRING (1).pptCP-STRING (1).ppt
CP-STRING (1).ppt
 
CP-STRING.ppt
CP-STRING.pptCP-STRING.ppt
CP-STRING.ppt
 
CP-STRING.ppt
CP-STRING.pptCP-STRING.ppt
CP-STRING.ppt
 

Recently uploaded

Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 

Recently uploaded (20)

Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 

Computer Programming- Lecture 5

  • 1. Lecture 5 C-Strings Computer Programming I 1
  • 2. Outline  C-strings  Functions for C-strings  C-strings input  C-strings output  C-strings to numbers Computer Programming I 2
  • 3. Problems  How do I store the names of students?  How do I specify filenames?  How to I manipulate text? Computer Programming I 3
  • 5. 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]; Computer Programming I 5
  • 6. 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]; 0 1 2 3 4 item int Computer Programming I 6
  • 7. 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]; Computer Programming I 7
  • 8. 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: s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9] H i M o m ! 0 ? ? Computer Programming I 8
  • 9. 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' Computer Programming I 9
  • 10. 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'}; Computer Programming I 10
  • 11. 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'}; Computer Programming I 11
  • 12. C-style string A C-style string in C++ is The declaration: basically an array of characters, terminated by a char name[10]="Hello"; null character ('0') is equivalent When we count the length of the string, char name[10]={'H','e','l','l','o','0'}; we do not count the terminating null character. H e l l o 0 (the size of the array is 10, the length of the string is 5) Computer Programming I 12
  • 13. The declaration: If the size of the array is not char name[]="Hello"; specified, then the array size would be equal to the is equivalent length of the string plus 1 char name[]={'H','e','l','l','o','0'}; H e l l o 0 (the size of the array is 6, the length of the string is 5) Computer Programming I 13
  • 14. The declaration: The declaration: char name[6]="H"; char name[]="H"; is equivalent is equivalent char name[6]={'H','0'}; char name[]={'H','0'}; H 0 H 0 (the size of the array is 6, (the size of the array is 2, But the length of the string is 1) But the length of the string is 1) Computer Programming I 14
  • 15. Null string The declaration: (empty string) The declaration: char name[6]=""; char name[]=""; is equivalent is equivalent char name[6]={'0'}; char name[]={'0'}; 0 0 (the size of the array is 1, (the size of the array is 1, the length of the string is 0) the length of the string is 0) Computer Programming I 15
  • 16. The declaration: char name[]="H"; H 0 (the size of the array is 2, is NOT equivalent the length of the string is 1) char name='H'; H (this is not an array nor a string, it is simply a character) Computer Programming I 16
  • 17. char name[11]="John Connor"; J o h n C o n n o r Note: If you just want to have an array of characters, then this MAY be ok. 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. Computer Programming I 17
  • 18. 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 Computer Programming I 18
  • 19. 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 Computer Programming I 19
  • 20. #include <iostream> #include <cstring> strcpy() using namespace std; int main() { char source[] = "Judgement Day"; Copy one string into char dest[] = "Rise of the Machine"; another. Copy string strncpy(dest,source); source to dest, cout << "source = " << source << endl; cout << " dest = " << dest << endl; stopping after the } terminating null character has been moved. source = Judgement Day dest = Judgement Day 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 !!! Computer Programming I 20
  • 21. 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. Computer Programming I 21
  • 22. int main() { This is an initialization, it char dest[20] = "Judgement Day"; } is valid. int main() { int main() { char dest[20]; char dest[20]; dest = "Judgement Day"; strcpy(dest,"Judgement Day"); } } This is an assignment, it is NOT valid. Use strcpy to assign a c-string to another c-string WARNING : You cannot assign one string to another just as you can't assign one array to another !!! Use strcpy() function instead. Computer Programming I 22
  • 23. 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 Computer Programming I 23
  • 24. 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' Computer Programming I 24
  • 25. == 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."; Computer Programming I 25
  • 26. 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 Computer Programming I 26
  • 27. #include <iostream> #include <cstring> strcmp() using namespace std; Compare one string to another starting int main() { with the first character in each string and char string1[] = "Hello"; continuing with subsequent characters char string2[] = "Hello World"; until the corresponding characters differ char string3[] = "Hello World"; or until the end of the strings is reached. char string4[] = "Aloha"; int n; n = strcmp(string1, string2); cout << string1 << "tt" << string2 << "t==> " << n << endl; Hello Hello World ==> -1 n = strcmp(string2, string3); cout << string2 << 't' << string3 << "t==> " << n << endl; Hello World Hello World ==> 0 n = strcmp(string3, string4); cout << string3 << 't' << string4 << "tt==> " << n << endl; } Hello World Aloha ==> 1 Computer Programming I 27
  • 28. #include <iostream> #include <cstring> using namespace std; int main() { char string1[] = "Hello"; char string2[] = "Hello"; if ( string1==string2 ) cout << "Same"; output: else Different 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. Computer Programming I 28
  • 29. #include <iostream> #include <cstring> using namespace std; int main() { char string1[] = "Hello"; char string2[] = "Hello"; if (strcmp(string1,string2)==0 ) cout << "Same"; output: else Same cout << "Different"; } Use strcmp() function instead for string comparison. Computer Programming I 29
  • 30. 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" Computer Programming I 30
  • 31. 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); Computer Programming I 31
  • 32. #include <iostream> #include <cstring> strcat() using namespace std; int main() { char dest[30] = "Rise of "; Appends one string to char source[] = "The Machine"; another. strcat() appends a copy of strcat( dest, source ); source to the end of cout << " dest = " << dest << endl; dest. The length of cout << "source = " << source << endl; the resulting string is } strlen(dest) + dest = Rise of The Machine strlen(source). source = The Machine 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 !!! Computer Programming I 32
  • 33. char s1[12]="Hello"; char s2[]="World"; s1 s2 H e l l o 0 W o r l d 0 strcat(s1,s2); s1 s2 H e l l o W o r l d 0 W o r l d 0 Computer Programming I 33
  • 34. 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 Computer Programming I 34
  • 35. C-string Output  C-strings can be output with the insertion operator  Example: char news[ ] = "C-strings"; cout << news << " Wow." << endl; Computer Programming I 35
  • 36. 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 Computer Programming I 36
  • 37. Simple C-String Input and Output must #include this for using Consider this program : strlen() function #include <cstring> Declaring name to be an #include <iostream> array of characters using namespace std; int main() { To treat the array of characters as C- char name[10]; string, we just use the name of the cout << "Name => "; array when dealing with I/O stream. cin >> name; cout << "Name is [" << name << "]" << endl; cout << "Name length is " << strlen(name); } Standard function to return the length of the string Computer Programming I 37
  • 38. #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: Sample run 2: Name => Hello there Name => hello Name is [Hello] Name is [hello] Name length is 5 Name length is 5 [remark: the cin will stop [remark: no problem] scanning after the space character is encountered. Computer Programming I 38
  • 39. 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 Computer Programming I 39
  • 40. Using getline  The following code is used to read an entire line including spaces into a single C-string variable  char a[80]; cout << "Enter input:n"; cin.getline(a, 80); cout << a << End Of Outputn"; and could produce: Enter some input: Do be do to you! Do be do to you!End of Output Computer Programming I 40
  • 41. 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 Computer Programming I 41
  • 42. More C-String Input and Output Sample run: consider: Name => HelloThereHowAreYou #include <cstring> Name is [HelloThereHowAreYou] #include <iostream> Name length is 19 using namespace std; int main() { char name[10]; cout << "Name => "; cin >> name; cout << "Name is [“ << name << "]n"; cout << “The Length: “ << strlen(name); } 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 !!!] Computer Programming I 42
  • 43. Input functions : character array input using cin.get(...) #include <iostream> sample run 1: only 9 using namespace std; character alibabamuthu int main () { [alibabamu] read, NOT 10. char name[20]; user press cin.get(name,10); sample run 2: enter, stop ali reading cout << "[" << name << "]"; because 'n' is [ali] } the default delimiter. Specifies the maximum number of bytes to be filled into the character 9 characters read, array, in the case here, 10 character including 2 tab 't' characters. will be filled, meaning 9 characters sample run 3: will be read (NOT 10) from input ali baba muthu stream, the 10th character is null [ali baba ] character ("0'). Computer Programming I 43
  • 44. #include <iostream> sample run 1: using namespace std; same as alibabamuthu before int main () { [alibabamu] char name[20]; cin.get(name,10,'z'); sample run 2: user press enter, 'n' cout << "[" << name << "]"; ali is read as baba } valid input muthu since 'n' is [ali NOT the baba delimiter. ] the character 'z' is used as delimiter the delimiter sample run 3: (which is 'z' in this afizuddin case) is encounter, [afi] thus stop reading Computer Programming I 44
  • 45. #include <iostream> using namespace std; int main () { output: char name[20]; ab cde cin >> name; [ab] cout << "[" << name << "]"; } #include <iostream> using namespace std; output: int main () { ab cde char name[20]; [ab cde] cin.get(name,10); cout << "[" << name << "]"; } Remember : cin.get(...) read whitespaces as valid input character unless the whitespace is delimiter Computer Programming I 45
  • 46. Input functions : overcome delimiter problem using cin.getline(...) #include <iostream> using namespace std; sample run 1: int main () { mary [mary] This char name1[10],name2[10],name3[10]; peter solved the cin.getline(name1,10); [peter] delimiter john problem!! cout << "[" << name1 << "]n"; [john] cin.getline(name2,10); cout << "[" << name2 << "]n"; cin.getline(name3,10); cout << "[" << name3 << "]n"; } Computer Programming I 46
  • 47. #include <iostream> using namespace std; sample run 1: int main () { marypeter [mary] char name1[10],name2[10],name3[10]; pan cin.getline(name1,10,'p'); john [eter cout << "[" << name1 << "]n"; pan cin.getline(name2,10,'j'); ] cout << "[" << name2 << "]n"; carl [ohn cin.getline(name3,10,'a'); c] cout << "[" << name3 << "]n"; } Why? Computer Programming I 47
  • 48. Assigning Characters Into C-Strings #include <cstring> #include <iostream> Strings are treated just using namespace std; like an array of int main() { character values here. char str[11]; The null character is str[0] = 'H'; str[1] = 'I'; str[2] = '0'; used to indicate the cout << str << endl; end of the string when for (int i=0; i<=9; i++) str[i] = 'A' + i; processed by the str[i] = '0'; standard library such cout << str << endl; as puts() function. str[5] = '0'; for (int i=0; i<=10; i++) cout << "[" << static_cast<int>( str[i] ) << "]"; cout << endl; output: cout << str << endl; HI ABCDEFGHIJ str[5] = 'A'; cout << str << endl; [65][66][67][68][69][0][71][72][73][74][0] system("pause"); ABCDE } ABCDEAGHIJ Computer Programming I 48
  • 49. #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; } WARNING : You can not use arithmetic addition in order to concatenate two C-string. The compiler will give you compile-time errors. Computer Programming I 49
  • 50. Array of C-Strings The declaration: declares one string of which the maximum length is 29. char actor[30]; A c-string is an one-dimensional array of characters. How do I declared an array of c-strings? one solution: This declare an array of 5 strings, of which char actor[5][30]; 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 50
  • 51. char actor[4][10] = { "Arnold", "Nick", "Claire", "Kristanna" }; 0 1 2 3 4 5 6 7 8 9 actor[0] A r n o l d 0 actor[1] N i c k 0 actor[2] C l a i r e 0 actor[3] K r i s t a n n a 0 Computer Programming I 51
  • 52. Example: #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 Stallon 0 Arnold Schwarzenegger 1 Nick Stahl 2 Claire Danes Computer Programming I 3 Kristanna Loken 52
  • 53. 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 Computer Programming I 53
  • 54. 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 Computer Programming I 54
  • 55. C-string to long  Larger integers can be converted using the predefined function atol  atol returns a value of type long Computer Programming I 55
  • 56. 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 Computer Programming I 56
  • 57. Library cstdlib  The conversion functions atoi atol atof are found in the library cstdlib  To use the functions use the include directive #include <cstdlib> Computer Programming I 57
  • 58. C-String conversion to numbers #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 12 output: 1234 123 123 0 12.34 1234 123 123 0 12 Computer Programming I 58
  • 59. 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 Computer Programming I 59
  • 60. 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. Computer Programming I 60