ALIGARH MUSLIM UNIVERSITY Department of Computer Science Course: MCA CSM-1101: Problem Solving Using C++ Academic Session 2017-2018 Handout-7 Topic: String handling in C++. Teacher : Dr. Rafiqul Zaman Khan, Professor +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Objectives: To know what is string and how to handle it in C++? To know how to read and Print Strings in C++. To know about some important built-in C++ string functions and how to use them? To learn about string class and their member functions. What is String? A string is any sequence of characters enclosed in double quotes . There is no separate data type for strings as integer , float or double . The string data type can be considered as a char array . The difference is that a character variable can hold only one character but a string can have more than one character in a character array. For example, a string called name with 9 characters can be declared as: char name  = “I like C” ; Check for the double quotes, the char array size 9 . Here the name can be considered as one string or as an array of characters. That is if you refer name it is “ I like C ” and if you refer name it is ‘ I ’, name is ‘ ‘ (a blank ), name is ‘ l ’, name is ‘ i ’, and so on. The last character name is ‘\0’ which indicates a NULL character which is not displayed but is stored as last character of the string to indicate its end . Note : Strings are stored as arrays of characters and have a special ‘\0’ termination character called NULL appended (attached) to them to signify the end of the string . Note that if the number of characters including the ‘\0’ is more than the size of the array the results will be unpredictable . However, if the size of the array is more than the number of characters the extra spaces after the last ‘\0’ character are kept blank and not referred because the string ends at ‘\0’ . So, always make sure that the size of the array is sufficient for the string. For example, the above declaration would be wrong if we write char name  = “I like C” ; 1
The size can be ignored also. In that case the size is considered as that of the number of characters specified in the declaration. char name [ ] = “I like C” ; String Input/Output: The easiest way to input strings is by using the C++ library function gets (means get string). The gets( ) function reads a string of characters entered at the keyboard until you strike the enter key (carriage return) . The carriage return does not become part of the string; instead a null terminator ‘\0’ is placed at the end. For example , in the following program fragment char str ; gets (str) ; and if the user enters Rafiqul Zaman Khan and presses the enter key the string variable str has the characters “Rafiqul Zaman Khan” with ‘\0’ appended at the end but is not displayed.
You've reached the end of your free preview.
Want to read all 17 pages?
- Spring '18
- Computer Science, ASCII, endl, char c, Dr. Rafiqul Zaman Khan