Home  >  Article  >  Backend Development  >  How to define string variables in c++

How to define string variables in c++

下次还敢
下次还敢Original
2024-05-06 17:57:17953browse

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.

How to define string variables in c++

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:

  • length():Return The length of the string (number of characters).
  • empty(): Returns true if the string is empty, otherwise returns false.
  • compare(): Compare a string with another string.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn