Strings in C++
- String constant: A sequence of characters enclosed within “ “ is known as a string constant.
- String variable: An array of characters (ending with ‘\0’) is known as a string variable. Such a variable will be required to store name of a student, name of an employee etc.
- Using cin:
- Using gets():
- String printing String can be printed using different methods. Two of them are given below. Both the methods can be used to print an entire string even if there are more than one words.
e.g. “HELLO”
This will be stored in memory as follows:
H | E | L | L | O | \0 |
Every string will end with a special character known as null character (\0) whose ASCII code is 0.
“A”--> this is a string and it will be stored in stored memory as follows:
A | \0 |
‘A’ --> this is a character constant and will be stored in memory as follows:
A |
Only 1 byte
e.g. char name [30];
Now “name” is a string variable.
Even though a string variable is an array, we can read and display a string without using loops.
We can read a string in different ways. Two methods are given below:
i) Using cin.
ii) Using gets() function.
cin>>string variable;
e.g.
cin>>name; | cin>>name; |
input: abc | input: abc def |
output: abc | output: abc |
i.e. cin can read only one word. Reading will be terminated if there is a space or new line character or a tab character.
So, if we expect more than one word in a string cin should not be used.
gets(string variable);
gets() is a function declared in stdio.h which is meant for reading a string from the keyword. gets() can read more than one word. It reads a line of string. i.e. reading terminates only if gets() finds new line character (enter key) in the input.
e.g.
gets()name; | gets()name; |
input: abc | input: abc def |
output: abc | output: abc def |
i) Using cout:
cout << string;
e.g.
name
a | b | c | d | e | f | \0 |
cout << name;
output: abc def after printing the string, cursor remains on the same line.
ii) Using puts():
puts(string);
puts() is a function declared in stdio.h which is meant for printing a string on screen. After printing the string cursor goes to the next line.
e.g.
name
a | b | c | d | e | f | \0 |
puts(name);
output: abc def - -> cursor moves to next line.
Two Dimensional array of characters
A 2-D array of characters can be used for storing a collection of strings .Each row of a two dimensional array can be treated as a 1-D array. So, each row can be treated as a string variable.Consider the declaration:
Char s[100][30];
That means s[0] , s[1] , . . . [99] are string variables.
To read all strings:
for( i = 0; i<100; i++)
gets(s[i]);
To print all strings:
for( i = 0; i<100; i++)
puts(s[i]);
CACKLE comment system