Cpp - String String Introduction

Introduction

A string is a series of characters.

In C++, a string is an array of characters ending with a null character.

The null character is a special character coded as '\0'.

You can declare and initialize a string like any other array:

char my_string[] = { 'a','v', 's', '\0' }; 

The last character, '\0', is the null character that terminates the string.

C++ has a shorthand form of string initialization using a literal:

char my_string[] = "test"; 

This form of initialization doesn't require the null character; the compiler adds it automatically.

The string "test" is 5 bytes, including null.

You can use std::cin object to collect user input and store it in a variable:

std::cin >> my_string; 

The code above has two major problems.

  • if the user enters more characters than the size of the buffer, cin writes past the end of the buffer.
  • if the user enters a space, cin treats it as the end of the string and stops writing to the buffer.

To solve these problems, you can use a function from cin object called getline() with two arguments:

  • The buffer to fill
  • The maximum number of characters to get

The following statement stores user input of up to 18 characters (including null) and stores it in the my_string character array:

std::cin.getline(my_string, 18); 

The method also can be called with a third argument, the delimiter that terminates input:

std::cin.getline(my_string, 18, ' '); 

This statement terminates input at the first space. When the third argument is omitted, the newline character ( '\n') is the delimiter.

Demo

#include <iostream> 
 
int main() /*from   w  ww  . j  a  va 2 s .  c  om*/
{ 
    char name[50]; 
    char quest[80]; 
 
    std::cout << "\nWhat is your name? "; 
    std::cin.getline(name, 49); 
 
    std::cout << "\nWhat is your quest? "; 
    std::cin.getline(quest, 79); 
  
    std::cout << "\nName: " << name << std::endl; 
    std::cout << "Quest: " << quest << std::endl; 
 
    return 0; 
}

Result

Related Topics

Exercise