fork download
  1. //Devin Scheu CS1A Chapter 10, P. 588, #1
  2. //
  3. /**************************************************************
  4. *
  5. * DETERMINE LENGTH OF C-STRING
  6. * ____________________________________________________________
  7. * This program finds the number of characters in a C-string
  8. * entered by the user.
  9. * ____________________________________________________________
  10. * INPUT
  11. * inputString : The C-string entered by the user
  12. *
  13. * OUTPUT
  14. * stringLength : The number of characters in the string
  15. *
  16. **************************************************************/
  17.  
  18. #include <iostream>
  19. #include <iomanip>
  20.  
  21. using namespace std;
  22.  
  23. // Function to count length of C-string using pointer notation
  24. int getStringLength(const char* str) {
  25. const char* ptr = str;
  26. while (*ptr != '\0') {
  27. ptr++;
  28. }
  29. return ptr - str;
  30. }
  31.  
  32. int main () {
  33.  
  34. //Variable Declarations
  35. const int MAX_SIZE = 100; //OUTPUT - Maximum size of the input string
  36. char inputString[MAX_SIZE]; //INPUT - The C-string entered by the user
  37. int stringLength; //OUTPUT - The number of characters in the string
  38.  
  39. //Prompt for Input and Echo
  40. cout << "Enter a string (max 99 characters): ";
  41. cin.getline(inputString, MAX_SIZE);
  42. cout << inputString << endl;
  43.  
  44. //Calculate Length
  45. stringLength = getStringLength(inputString);
  46.  
  47. //Separator and Output Section
  48. cout << "-------------------------------------------------------" << endl;
  49. cout << "OUTPUT:" << endl;
  50.  
  51. //Output Result
  52. cout << left << setw(25) << "String Length:" << right << setw(15) << stringLength << endl;
  53.  
  54. } //end of main()
Success #stdin #stdout 0.01s 5284KB
stdin
Triangle
stdout
Enter a string (max 99 characters): Triangle
-------------------------------------------------------
OUTPUT:
String Length:                         8