strlen() sample program in C++
By: Tamil Selvan
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.
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.
Archived Comments
1. Very good. very clear. thank you
View Tutorial By: Andrei at 2012-12-16 04:29:36
2. haha
View Tutorial By: babak at 2010-01-19 08:44:20
3. hiiiiiii
it's good turotiral for strlen()_ program
http://BharatClic
View Tutorial By: Raju Singh at 2009-10-01 11:51:30
4. hiiiiiii
it's good turotiral for strlen()_ program
http://BharatClic
View Tutorial By: Raju Singh at 2009-10-01 09:47:04
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++