Wednesday 3 February 2016

How to use character array as strings in C++ program.

There are many different ways in which we can use strings in our C++ program and today we will find the best way to use a string in your program.
For now we will have look on the different ways of using String.
First way:
Since C++ is a super-set of C, so we can use the strings in the same style we used it C language. In C we say that :
string = array of characters.
So whenever we need to use a string we just make a array of characters.
EXAMPLE:
char str[50];  -> Here 'str' is an array of 50 characters
As we know that array is nothing be contiguous block of memory. So here we have 50 contiguous block of memory.
Since we are now in 2016 and thus using character buffer for string would be a very bad idea. Plus this is not memory efficient.
When we write char str[50] then the program will occupy 50 bytes of memory no matter whatever we store into it. So this is something we would never want to do. However this is just a brief description of why we should not use the character array in our normal practice.
Now I will tell you "how to accept strings from user?"
To accept string using the character array we just can't use the cin( or std::cin ) because this just stops reading when it will encounter a space. It sees a lexical token as a "string".
We can use cin.getline() :
char str[50];
cin.getline(str, sizeof(str));
instead of sizeof(str) we could have also used 50. see below:
char str[50];
cin.getline(str, 50);
Former is better than later.
REASON:
I would use sizeof(input) in place of 50 in the call to cin.getline(); because it would mean we can change the size of the input buffer and only need to change one line instead of two lines.

SIZE of str:
sizeof(str);
The size will always be 50 bytes.

TYPE of str:
typeid(str).name(); // comes under #include<typeinfo>
The type will be "Array of 50 characters".

Next I will tell you a good and efficient way to use strings in C++.
Thanks

1 comment: