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(("C++")) -.-> cpp/IOandFileHandlingGroup(["I/O and File Handling"]) cpp(("C++")) -.-> cpp/StandardLibraryGroup(["Standard Library"]) cpp(("C++")) -.-> cpp/SyntaxandStyleGroup(["Syntax and Style"]) cpp/BasicsGroup -.-> cpp/strings("Strings") cpp/IOandFileHandlingGroup -.-> cpp/output("Output") cpp/IOandFileHandlingGroup -.-> cpp/user_input("User Input") cpp/IOandFileHandlingGroup -.-> cpp/files("Files") cpp/StandardLibraryGroup -.-> cpp/string_manipulation("String Manipulation") cpp/SyntaxandStyleGroup -.-> cpp/code_formatting("Code Formatting") subgraph Lab Skills cpp/strings -.-> lab-96191{{"Determine String Length in C++"}} cpp/output -.-> lab-96191{{"Determine String Length in C++"}} cpp/user_input -.-> lab-96191{{"Determine String Length in C++"}} cpp/files -.-> lab-96191{{"Determine String Length in C++"}} cpp/string_manipulation -.-> lab-96191{{"Determine String Length in C++"}} cpp/code_formatting -.-> 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.