C++ String Basics

C++ strings store textual information. The string variable has a sequence of characters enclosed by double quotes.

In C++ string basics, we cover following topics.

Advertisements
  • Types of strings
  • How to initialise strings ?
  • How to read input strings ?

Types Of Strings

A string is a character array terminated by a null (\0)character. The C++ language allows us to declare two types of strings.

  1. C-style strings
  2. String objects from class string

C-style Strings

The C++ supports C-style strings which is a character array of fixed length. The length of the array is pre-determined or decided when the array is initialised. Each string ends with null character.

Initialise A C-style string

You can declare and initialize C-style string in following ways.

//string declaration
char name[3];    
//string initialisation
name[3] = "Ram";
//string declaration
char state[10]; 
state[10] = {'D','e','l','h','i'};
//declare & initialise at same time
char age[3] = {'2','5'};

When you Initialize the string leave square bracket empty. The size is decided by number of elements inserted into the array.

// string size not defined 
char pincode[] = "2342"; 
// string size not define here also
char pincode[] = {'2','3','5','8'};

The spaces required for a character array can be larger than its requirement.

char animal[30] = "Lion";

The space required for Lion is 4 space. However, there are 30 space available. Therefore, 26 memory space remain unused and wasted.

Important Features of C-style string

  • A null is automatically added at the end of the string.
  • If the string array has extra space than required. Then the memory space is wasted due to internal fragmentation.
  • Length of the array is fixed.
  • Due to its fixed length, the C-style string does not expand more than allocated spaces.

To solve the wastage problem, and make string dynamic.

String Objects From Class string

The C++ string class allows to create variable length string objects. Before you use the string class include the string header file as follows.

#include <string.h>

Depending on the C++ compiler, the file name may differ. Refer to your compiler documentation. For example, Dev C++ 5.11 uses <cstring> .

Initialize String Objects

To initialize string object use one of the following method.

string s = "Hello World!"; // declare and assign value
string p = s;             // assign another string
 
char s[] = "Raju";
string m = string(s);     // convert the character array and assign
string x("Mumbai");       // use the constructor 

Important Features of String Objects

  • The string objects are dynamic and of variable length. The object can shrink or expand because the internal memory is adjusted automatically.
  • If you do not initialize a string, then a string of length 0 is created.
  • The string object may or may not terminate with a null.
  • C++98, C++1 and above offers a wide range of functions to manipulate string objects.

Reading String Inputs

A C++ program receives input from users through input stream (istream). Use one of the member from class istream to receive string inputs.

MethodClass name
cinObject of class istream
get() Public function of class istream
getline()Public function of class istream

cin

The cin is an object of class istream that read input characters from input device such as keyboard. Since , cin is associated with the standard C input stream (studio.h) , it puts the program on wait while user enters the input.

The input is stored in a variable with the help of an extraction operator (>>).

cin >> name;
Advertisements

There is problem reading strings with cin object. Consider the following example.

Example#2

//Program written using Dev C++ 5.11
#include <iostream>
#include <cstring>
#define SIZE 15
using namespace std;
int main ()
{
   char Name [SIZE];
   char State [SIZE];
   
   std::cout << "Enter Name:" << "\n";
   std::cin >> Name;
   std::cout << " Enter State:" << "\n"; 
   std::cin >> State; 
   //Printing output
   std::cout >> "Your name is" >> Name >> std::endl; 
   std::cout >> " Your state is:" >> State >> endl; 
   system ("pause");
   return 0;
}

Output#2

Enter Name: 
John
Enter State:
Doe

The cin stop taking input as soon as a white-space , a tab, or a newline is encountered. Therefore, if user enters ” John doe”. The first part is read and second part remain in the stream. The cin takes it as input for state.

get()

The get () and getline () are two functions that read input characters until a newline character or end of the file is met. The main difference between get() and getline() is that the get() function adds a newline at the end of the string.

The syntax to read a C-style string using get() function is given below.

//Syntax for C-style strings
istream& get (char* s, streamsize n);
istream& get (char* s, streamsize n, char delim);
//example:
char name[10];
cin.get(name, 10);
cin.get(name, 10, '\n');

<span style="color:#cf2e2e" class="tadv-color">s</span> – It is the pointer to character array.

<span style="color:#cf2e2e" class="tadv-color">n</span> – Number of characters to write in the string s including null. It should not be less than 2.

If you want to read only one character use get().

<span style="color:#cf2e2e" class="tadv-color">delim</span> – You may set an explicit delimiting character to end the input. The default is newline (\n).

getline ()

The getline() is also read line from the standard input stream (stdio), but it store the string without null.

Use following syntax to read character array.

// Syntax to read character array
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
//Example
char s[10];
cin.getline(s, 10);
cin.getline(s, 10,'-');

You can receive string object as input using getline ().

// Syntax for String object
istream& getline (istream& is, string& str, char delim);
istream& getline (istream& is, string& str);
//Example
string name;
getline (cin, name);
getline (cin, name, '\n');

<span style="color:#cf2e2e" class="tadv-color">is</span> – stream object from which characters are extracted. Ex. cin.

<span style="color:#cf2e2e" class="tadv-color">str</span> – the string object to store line of text. Any previous entry will be overwritten.

<span style="color:#cf2e2e" class="tadv-color">delim</span> – you can specify an explicit delimiter instead of default newline.

Example#3

//C++ program to receive input using //getline () written using Dev C++ 5.11
#include <iostream>
#include <cstring>
#define SIZE 15
using namespace std;
int main ()
{
    //string declaration
    char name[SIZE];
    string age;
    
    //read input strings
    cout << " Enter Name: " << '\n';
    cin.getline(name, 15);
    cout << " Enter Age : " << '\n';
    getline (cin, age);
    //print output 
    cout << " Your name is " << name << 
    ". Your age is " << age << endl; 
    
    return 0;
}

Output#3

Enter Name: 
John Doe 
Enter Age: 
56
Your name is John Doe. Your age is 56.

References

  • Cplusplus.com. 2020. Istream::Getline – C++ Reference. [online] Available at: <http://www.cplusplus.com/reference/istream/istream/getline/> [Accessed 18 April 2020].
  • Cplusplus.com. 2020. Istream::Getline – C++ Reference. [online] Available at: <http://www.cplusplus.com/reference/istream/istream/getline/> [Accessed 18 April 2020].
  • Sheth, T. (2015). C++ Primer Plus (6th ed., pp. 120-139). Pearson Education India.
  • Bronson, G., & Borse, G. (2010). C++ for engineers and scientists (p. 140). Thomson Course Technology.
  • Balagurusamy, E. (2008). Object oriented programming with C (pp. 428-431). Tata McGraw-Hill.


Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.