Introduction
In this lab, we will learn how to find the length of a string entered by the user in C++ programming language.
In this lab, we will learn how to find the length of a string entered by the user in C++ programming language.
Create a new C++ file named main.cpp
in the ~/project
directory.
cd ~/project
touch main.cpp
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;
We will declare a string variable and read the input entered by the user.
string myString;
cout<<"Enter a string: ";
getline(cin,myString);
length()
functionWe will calculate the length of the string entered by the user using the length()
function.
int length = myString.length();
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;
#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;
}
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.