Programming Tutorials

strlen() sample program in C++

By: Tamil Selvan in C++ Tutorials on 2007-09-17  

The most popular library is almost certainly the string library, with perhaps the function strlen() called most often. strlen() returns the length of a null-terminated string. Listing below illustrates its use.

strlen().

1:     #include <iostream.h>
2:     #include <string.h>
3:
4:     int main()
5:     {
6:        char buffer80];
7:        do
8:        {
9:           cout << "Enter a string up to 80 characters: ";
10:          cin.getline(buffer,80);
11:          cout << "Your string is " << strlen(buffer);
12:          cout << " characters long." << endl;
13:       }    while (strlen(buffer));
14:       cout << "\nDone." << endl;
15:     return 0;
16: }

Output: Enter a string up to 80 characters: This sentence has 31 characters
Your string is 31 characters long.
Enter a string up to 80 characters: This sentence no verb
Your string is 21 characters long.
Enter a string up to 80 characters:
Your string is 0 characters long.

Done.

Analysis: On line 6, a character buffer is created, and on line 9 the user is prompted to enter a string. As long as the user enters a string, the length of the string is reported on line 11.

Note the test in the do...while() statement: while (strlen(buffer)). Since strlen() will return 0 when the buffer is empty, and since 0 evaluates FALSE, this while loop will continue as long as there are any characters in the buffer.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)