Calculate Length of a String in C++

0

In this example, a string variable will be taken from a user as an input and a function will be performed on it which will tell us the exact length of the string.

#include <iostream>
using namespace std;

int main()
{
    string str;

    cout << "Please enter a string: ";
    cin >> str;
    
    cout << "Size of the string using size function is: ";
    cout << str.size();
    cout << endl;
    
    cout << "Size of the string using length function is: ";
    cout << str.length();
    return 0;
}

A string variable str is used to store the string input from the user. The size() function or length() function is used to calculate the length of a string. Both functions are exactly the same and perform the same operation.

In line 11, the length of the string is calculated and displayed on the console using the size() function. In line 13 the length of the string is calculated and displayed on the console using the length() function.

Output

Please enter a string: Hello World
Size of the string using size function is: 5
Size of the string using length function is: 5

LEAVE A REPLY

Please enter your comment!
Please enter your name here