The programmer wanted to test out his own version of strlen. The function is simple enough, but maybe it's too simple. So what's the length of the following strings?
Sam
This is a test
Hello World
1 /************************************************
2 * Compute the length of a string entered by *
3 * the user. *
4 ************************************************/
5 #include <iostream>
6
7 /************************************************
8 * length -- Find the length of a string *
9 * (strlen does a better job.) *
10 * *
11 * Returns: *
12 * length of the string. *
13 ************************************************/
14 static int length(
15 const char string[] // String to check
16 )
17 {
18 int index; // index into the string
19
20 /*
21 * Loop until we reach the
22 * end of string character
23 */
24 for (index=0; string[index] != '\0';++index)
25 /* do nothing */
26
27 return (index);
28 }
29
30 int main()
31 {
32 char line[100]; // Input line from user
33
34 while (1) {
35 std::cout << "Enter a string: ";
36 std::cin.getline(line, sizeof(line));
37
38 std::cout << "Length is " <<
39 length(line) << '\n';
40 }
41 return (0);
42 }