fork download
  1. // Diego Martinez CSC5 Chapter 10, P.588,#1
  2. /*******************************************************************************
  3. * DISPLAY STRING LENGTH
  4. * ______________________________________________________________________________
  5. * This program asks the user to enter a string. A function is used to count
  6. * the number of characters in the C-string and return the length of the string.
  7. *
  8. * Computation is based on the Formula:
  9. *
  10. * length = number of characters before the null terminator ('\0')
  11. *
  12. * ______________________________________________________________________________
  13. * INPUT
  14. *
  15. * User string
  16. *
  17. * OUTPUT
  18. *
  19. * Length of the string
  20. *
  21. *******************************************************************************/
  22.  
  23. #include <iostream>
  24. #include <cstring>
  25. using namespace std;
  26.  
  27. // Function prototype
  28. int stringLength(const char *);
  29.  
  30. int main()
  31. {
  32. // Variable declaration
  33. char userString[100];
  34. int length;
  35.  
  36. // User input
  37. cout << "Enter a string: ";
  38. cin.getline(userString, 100);
  39.  
  40. // Function call
  41. length = stringLength(userString);
  42.  
  43. // Output result
  44. cout << "The length of the string is: " << length << endl;
  45.  
  46. return 0;
  47. }
  48.  
  49. // Function definition
  50. int stringLength(const char *str)
  51. {
  52. int count = 0;
  53.  
  54. // Count characters until null terminator
  55. while (*(str + count) != '\0')
  56. {
  57. count++;
  58. }
  59.  
  60. return count;
  61. }
Success #stdin #stdout 0s 5312KB
stdin
Diego
stdout
Enter a string: The length of the string is: 5