Characters Everything stored or manipulated by a computer is

Characters

Everything stored or manipulated by a computer is at its core a number. This goes without saying for the C++ types int, float, and double, but it is also true of the bool and char types.

Execute the program and observe that when a char variable is printed with cout, the character corresponding to the stored number is displayed; when the same stored number is printed in an int variable, the number itself is displayed. The numbers used for characters are defined by the American Standard Code for Information Interchange (ASCII); numeric codes from 0 to 127 are assigned to 128 common characters. The pairing of codes with characters, some of which are depicted in Table 1, may appear to be somewhat arbitrary, but at least everyone using ASCII uses the same numbers.

Table 1: Significant ASCII Codes

Character-Testing Functions

The cctype library contains several functions for testing characters. These functions expect a single character as a parameter and return either true or false. Table 2 lists and describes the functions that can be found in this library.

Table 2: cctype Character Testing Functions

To demonstrate the use of these functions, include the limits library and add the following code to function main; execute the program and test various types of characters such as a letter, a digit, a space, a curly brace, etc.

Character Case Conversion

In addition to the character testing functions, there are two functions that will convert a character to lowercase or uppercase. Table 3 lists and describes these functions.

Table 3: cctype Character Case Conversion Functions

To demonstrate the use of these functions, add the following code to function main; execute the program and test various types of characters such as a letter, a digit, a space, a curly brace, etc.

C-Style Character Strings

Consider now how memory is used to store a person\'s name. The C convention for storing a sequence of related characters as a character string, or C-string, places them in consecutive memory (as in an array) followed by a null character, the ASCII code for which is 0; the null character is typically written as \'\\0\'. Because of the null character, the minimum storage for a C-string is the number of characters plus one. Thus the name \"Smith\" would require an array of six characters. Add the following to function main.

The characters would be stored as depicted in Figure 1.

Figure 1: C-Style Character String in Memory

As with any array, name, the name of the array, holds the memory address of the first element, or character. The iostream library defines cin and cout to behave specifically for C-strings. In the case of cout, the reference is followed to its character, the character is printed, and so is every character following it until a null character is encountered. Add the following to function main.

Execute the program to see that in the entire string is printed as described, stopping only at the null character. In the second, a single char value, the first in the string, it is printed by itself.

Add two more lines to function main.

Execute the program again and observe that printing now stops after three characters because a null character has been manually inserted into the string at that point. Add three more lines to function main.

Execute the program yet again, noting that the fourth character ([3]) has been restored and the sixth character ([5]) replaced; the sixth character was the null character which ended printing. With it replaced, printing may now continue past the end of the name. Execute it and observe how many characters are printed. This number is unpredictable, as printing stops when a null character is chanced upon in memory.

For a C-string, a cin statement reads characters from the keyboard and places them one at a time into successive positions beginning at the given pointer location until whitespace is encountered; whitespace includes characters such as the space, the tab, and the newline. Add the following to function main.

Execute the program to verify that it works correctly.

It is important to note that no attempt is made to control the number of characters read from the keyboard. If the number read exceeds the size of the array allocated, unpredictable behavior may result as the memory written can overlap with that reserved for other variables. Add the following to function main.

Special Compilation Instructions! Modern compilers come equipped with some built-in protection against the type of buffer overrun that this code is about to demonstrate; unfortunately, since we want to see the potential danger, we need to turn this protection off. When you compile this code, add the compiler flag -fno-stack-protector to your compiler command.

Execute the program (after compiling with stack protection disabled), and enter a very long name when prompted.

A small program such as this may very well execute correctly, but problems are inevitable as program size and complexity increase.

To control the number of characters read from the keyboard, use cin\'s getline method. Modify the previous code as follows.

A bonus of the getline method is that we can now input whitespace.

C-Style Character String Functions

There are a variety of string-handling functions available for use with C-strings. Four of the most useful of these are strlen, strcmp, strncpy, and strncat.

The String Length Function: strlen

As stated earlier, every C-string ends with the null character, \'\\0\'. Function strlen, read aloud as string length, determines the number of characters in a C-string by counting until the null character is reached. Add the following to function main.

Execute the program to verify that strlen behaves as described with a constant character string.

Function strlen can also be used with variables. Add the following to function main.

Examine the results of executing this addition.

C-strings may also be read in at run-time and then inspected for length. Add the following to function main.

Execute the program once more, taking note that the city name should not exceed the twenty character limit imposed by the C-string variable definition. Experiment to determine what happens if the length does exceed this limit.

The String Compare Function: strcmp

A common need of strings is the ability to compare them. The following addition to function main represents a common mistake when beginning to work with C-strings.

Compile the program and examine any error that results. See Figure 1 for an interpretation of this error (if it occurs). Some compilers may produce an error message in this situation, while others may not... In either case, it is still an error!

The variable names state and state2 each correspond to a location in memory which holds the address of the first of the twenty-one characters associated with the C-string when it was defined. As it does with any operands, regardless of type, the relational operator < accomplishes its goal via subtraction; the left hand operand is subtracted from the right hand, with the result being true for a positive result and false otherwise. Subtracting addresses would provide no useful information in this context.

The above expression can be rewritten using the string function strcmp, read aloud as string compare, to effectively subtract the characters (not the address) of the left hand side of a relational expression from the characters associated with the right hand side of the expression.

The strcmp function compares successive pairs of characters in its operands, continuing only so long as they are the same. The first inequality returns a negative result if the first operand is the smaller or a positive result if it is larger; should both strings be the same throughout, a zero is returned.

Table 4: strcmp Function\'s Return Results Interpreted

Replace the comparison in the program code given above with the following.

Execute the program to verify the desired behavior.

The String Copy Function: strcpy and strncpy

When working with strings, it is often desirable to initialize a string to a particular value. While this is possible with C-strings at the time of declaration (as seen in previous examples), it is not possible any other time. The following addition to function main represents another common mistake when beginning to work with C-strings.

Compile the program and examine the error that results. See again Figure 1 for an interpretation of this error. The variable name city corresponds to a single location in memory, one which holds the address of the first of the twenty-one characters associated with city when it was defined. The assignment operator = is being asked here to move something in to replace the location in city; if this were allowed, there would be no way to ever find the twenty-one characters already set aside.

The above expression can be rewritten using the string function strcpy, read aloud as string copy, to effectively copy the characters on the right hand side of an assignment expression to the characters associated with the left hand side of the expression.

The strcpy function copies characters from sourceStr and places them into destinationStr beginning at the first element.

Modify the previous line of code as follows.

Execute the program to verify the expected behavior of strcpy.

One C-string variable can also be copied into another; add the following to function main.

Execute the program again.

Another frequently required task is to interchange the contents of two strings. To see how this is done, imagine a red cup of coffee in one hand and a blue cup of orange juice in the other; how are the contents switched? If one were very quick and very lucky, simultaneous wrist flips followed immediately by hands changing places might accomplish the task; it is far more likely that a mess would result. A simpler and more predicatable outcome can be arrived at by using a third cup and a series of three pours. This is what is done to interchange two C-strings in memory. Add the following to function main.

Execute the program to verify that the swap takes place as predicted.

One problem encountered with strcpy is the possibility of exceeding the bounds of the destination array. The following code will result in storage beyond the bounds of the character array. As an example, the longest legal city name in the United States is recorded as Rancho Santa Margarita in California; the name contains twenty-two characters, including spaces. Add the following to function main and execute the program.

strncpy performs the same operation as strcpy with the added ability to specify how many characters to copy.

The strcpy function copies numberCharsToCopy characters from sourceStr and places them into destinationStr beginning at the first element.

Replace the previous call to strcpy with the call to strncpy as shown below.

The String Concatenation Function: strcat and strncat

Another common need when working with strings is the ability to join or concatenate two strings together. A common mistake in attempting to concatenate two strings is to use the + operator to perform the action. Add the following to function main.

The correct way to perform string concatenation with C-strings is to use the strcat function.

The strcat function, pronounced string cat, will copy the characters in str2 placing them at the end of str1 beginning in the location occupied by the null character. Add the following to function main and execute the program to verify strcat\'s performance.

Once again, there is no bounds checking; it is conceivable that the combination of str1 and str2 will contain more characters than originally set aside for str1. The strncat function allows only a specified number of characters to be concatenated, but it does not automatically place the \'\\0\' null terminator for you, so you must be sure to insert it explicitly:

Add the following to function main and execute the program.

Verify the output is as expected.

The std::string Object

The C++ string library introduces a std::string object which allows for easier string handling.

As we have seen previously, to use a std::string object, include the string header and add the following to function main to declare, read and display a string.

Execute the program to verify the use of std::string.

As before, cin will stop reading once whitespace is encountered. To read everything typed until the Enter key is pressed, use the getline function. Replace the cin from above with the following and execute the program.

The std::string Length Method

The std::string object has several methods one of which is length(). The length() method will return the length of the string stored in the std::string object. The following demonstrates its use.

Execute the program to verify the use of the length() method.

Comparing std::strings

While C-strings must employ the strcmp function, std::string objects can be compared using the relational operators. Copy the following into function main and execute the program repeatedly to fully test the selection structure.

Copying std::strings

The assignment operator can be used to copy a std::string. Copy the following into function main and execute the program.

Concatenating std::strings

The arithmetic addition operator can be used to concatenate strings. Copy the following into function main and execute the program.


Notice that no care is taken concerning the amount of storage available during the copy and concatenation in the previous examples. The std::string object will automatically expand its capacity as needed. This is yet another way std::string is much easier to use than character arrays.

C-Style String from std::string Object

While the std::string object is much easier to use, there are still occasions that will require the use of a C-string. One such example is the fstream object which expects a filename as a C-string.

The std::string object provides a method which can be utilized to obtain the current contents of the std::string object as a C-string. Include the necessary library and add the following to function main.

Execute the program, then verify the contents of the file.

\"Verbatimcode.png\" Code Illustration
     char ch = \'A\';     int i = ch;     cout << \"A: \" << ch << \' \' << i << endl;  

Solution

1) to print the ASCII values of the given character

2) program to change case of the given input

#include<stdio.h>
#include<string.h>

int main(){

  char str[20];

  int i;

printf(\"Enter any string->\");

scanf(\"%s\",str);

printf(\"The string is->%s\",str);

  for(i=0;i<=strlen(str);i++){

      if(str[i]>=65&&str[i]<=90)

       str[i]=str[i]+32;

}

printf(\"\ The string in lower case is->%s\",str);

  return 0;

}

Characters Everything stored or manipulated by a computer is at its core a number. This goes without saying for the C++ types int, float, and double, but it is
Characters Everything stored or manipulated by a computer is at its core a number. This goes without saying for the C++ types int, float, and double, but it is
Characters Everything stored or manipulated by a computer is at its core a number. This goes without saying for the C++ types int, float, and double, but it is
Characters Everything stored or manipulated by a computer is at its core a number. This goes without saying for the C++ types int, float, and double, but it is
Characters Everything stored or manipulated by a computer is at its core a number. This goes without saying for the C++ types int, float, and double, but it is

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site