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

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /