C++ Programming

Character Array in C++

Character Array stores the more than one character in sequence. For example if you want to store the name like “Saleem” which is collection of character then you can store this name in character array. (Although C++ sport String Class which we discuses in next Tutorials).


Char sname[50];

There is no need that you store one by one character in array like integer array.

For example sname[0]=’a’; and sname[1]=’b’ and up to son

You can also give out put with cout statement like


Cout>>sname;

But with CIN statement you can take a single string when you press space or enter Key, a null character will be place in the end of array which tells to compiler that user input is completed.

For example if you want to store the name like “Tauqeer Shah” so you can’t use cin for this purpose.

You can use gets() function which take a single line of string when you press Enter Key then your input will be complemented.

For example if you want to store the name “Tauqeer Shah” then you can use


Gets(sname);

Now we take a programming example in which we declare an array which get a name at run time and then display this name on screen.


#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
char sname[50];
gets(sname);
cout<<endl;
cout<<sname;
return 1;
}

Now if you want to store more than one name then you can also use two dimensional character arrays.

For example


Char sname[4][50];

Which store 4 names and each name have maximum 50 characters.

We take a programming example to understand the above line.


#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
char sname[4][50];
int i;
cout<<"Enter 5 name after each name press Enter Key"<<endl;
for(i=0;i<=3;i++)
gets(sname[i]);

cout<<"your names in Array are"<<endl;
for(i=0;i<=3;i++)
cout<<sname[i]<<endl;
return 1;	
}

Above program take 4 names. The maximum length of each name is 50 characters.