C++ Strings are categorized in two ways.
- Character String
- String Class
Character String
Character string in c++ is an array of characters enclosed within a double quote. It mainly consists of any alphabets, characters, digits, or special symbols.
The last character of the string will be the null character “\0” to terminate the string. The compiler added it automatically.
Syntax: Character string
char string_name [length] ="value"
- Char: is the data type for a string in c++
- String_name: is the actual name given to the string array
- Length: it specifies the max length of an array
- Value: it is the actual string stored in the character string
Example 1
char name [20] "john mike";
String input
There are three ways to input a string from the user.
cin: general-purpose input, does not support spaces
cin.getline(): used to take a string of characters from the user including spaces
cin.get(): use to take the single character of string
Example 2:
//char string in C++
#include <iostream>
using namespace std;
int main() {
string enterString;
cout << "Enter any string: ";
getline (cin, enterString);
cout << "Your entered: " << enterString;
return 0;
}
Output
Enter any string: john mike
Your entered: john mike
Class String
C++ standard library provides a string class as a template that does all the c-styling string tasks automatically with a lot of enhanced functionality.
Syntax: String Class
string name="Value";
Example
string name = "john mike"