The string data type is used to define string variables in C, such as string name; initialized through assignment operators, such as name = "John Doe"; and obtaining values using << operators, such as cout << ; name; String attributes: length() returns the length, empty() checks if it is empty, compare() compares with another string.
Definition of string variables in C
Definition of string variables
In C, string variables are used to store and manipulate text. To define a string variable, we use the string data type, followed by the variable name:
<code class="cpp">string variableName;</code>
For example:
<code class="cpp">string name;</code>
Initialize the string variable
In After defining the string variable, we can initialize it through the assignment operator (=):
<code class="cpp">name = "John Doe";</code>
At this time, the variable name stores the text "John Doe".
Get the value of a string variable
To get the value of a string variable, we can use the << operator:
<code class="cpp">cout << name;</code>
This The value of variable name will be printed in the console.
Properties of string variables
String variables have the following properties:
Example
The following is an example of using a string variable:
#include
#include
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
getline(cin, name);
cout << "Your name is " << name << endl;
return 0;
}
In this example, we define a string type variable name, then reads a string from the user input and stores it in name. Finally, we use the cout statement to print the value of the variable name.
The above is the detailed content of How to define string variables in c++. For more information, please follow other related articles on the PHP Chinese website!