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

How to define string variables in c++

下次还敢
Release: 2024-05-06 17:57:17
Original
999 people have browsed it

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>
Copy after login

For example:

<code class="cpp">string name;</code>
Copy after login

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>
Copy after login

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>
Copy after login

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!

Related labels:
c++
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template