fork download
  1. //Cameron Pham CS1A Chapter 10, p. 588, #1
  2. //
  3. /******************************************************************************
  4. * COUNT STRING LENGTH
  5. * ______________________________________________________________________________
  6. * This program accepts a string and passes it to a function. The function counts
  7. * the number of characters in the C-string. It then returns the total character
  8. * count.
  9. * ______________________________________________________________________________
  10. * INPUT
  11. * String // Characters inputted
  12. *
  13. * OUTPUT
  14. * Length // Counted characters
  15. *******************************************************************************/
  16. #include <iostream>
  17. using namespace std;
  18.  
  19. // Function prototype
  20. int stringLength(char* str);
  21. int main()
  22. {
  23. const int SIZE = 100;
  24. char userString[SIZE];
  25. int length;
  26. // Get a string from the user
  27. cout << "Enter a string: ";
  28. cin.getline(userString, SIZE);
  29. // Calculate the string length
  30. length = stringLength(userString);
  31. // Display the string length
  32. cout << "The length of the string is: " << length << endl;
  33. return 0;
  34. }
  35. // Count the characters in a C-string
  36. int stringLength(char* str)
  37. {
  38. int count = 0;
  39. // Count characters until the null terminator is reached
  40. while (*(str + count) != '\0')
  41. {
  42. count++;
  43. }
  44. return count;
  45. }
Success #stdin #stdout 0s 544KB
stdin
Hello World
stdout
Enter a string: The length of the string is: 11