Determine String Length in C++

C++C++Beginner
Practice Now

Introduction

In this lab, we will learn how to find the length of a string entered by the user in C++ programming language.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp/BasicsGroup -.-> cpp/variables("`Variables`") cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") subgraph Lab Skills cpp/variables -.-> lab-96191{{"`Determine String Length in C++`"}} cpp/data_types -.-> lab-96191{{"`Determine String Length in C++`"}} end

Create a new C++ file

Create a new C++ file named main.cpp in the ~/project directory.

cd ~/project
touch main.cpp

Include the necessary header files

In order to work with strings in C++, we need to include certain header files. We will use the <iostream> and <string> header files in our program.

#include <iostream>
#include <string>

using namespace std;

Declare a string variable and read the input

We will declare a string variable and read the input entered by the user.

string myString;
cout<<"Enter a string: ";
getline(cin,myString);

Calculate the length of the string using length() function

We will calculate the length of the string entered by the user using the length() function.

int length = myString.length();

Display the length of the string

We will display the length of the string calculated in the previous step using the cout statement.

cout<<"The length of the string is: "<< length << endl;

Full code example

#include <iostream>
#include <string>

using namespace std;

int main() {
    string myString;
    cout<<"Enter a string: ";
    getline(cin,myString);
    int length = myString.length();
    cout<<"The length of the string is: "<< length << endl;
    return 0;
}

Summary

In this lab, we learned how to find the length of a string entered by the user using length() function in C++ programming language. We also learned how to display the length of the string in the terminal using cout statement.

Other C++ Tutorials you may like