fork download
  1. //Maxwell Brewer CS1A Chapter 10, p. 588, #1
  2. //
  3. /*******************************************************************************
  4.  * COUNT ARRAY CHARACTERS
  5.  * _____________________________________________________________________________
  6.  * This program will take a string and output the number
  7.  * of characters contained in the string array.
  8.  *
  9.  * INPUT:
  10.  * input_string : user input of characters
  11.  *
  12.  * OUTPUT:
  13.  * charCount : array of string characters
  14.  *
  15.  ******************************************************************************/
  16.  
  17. #include <iostream>
  18. using namespace std;
  19.  
  20. // Function prototype
  21. int charCount(char*);
  22.  
  23. int main() {
  24.  
  25. // Declare char array for the C-string, size 21
  26. //(20 characters + null terminator)
  27. char input_string[21];
  28.  
  29. // Prompt user to enter input
  30. cout << "Enter a string with a maximum of 20 characters:\n";
  31. cout << "I will output the number of characters it has!\n";
  32.  
  33. // Read input up to 20 characters
  34. cin.getline(input_string, 21); // not using cin >>
  35. // since it stops at
  36. // whitespace
  37.  
  38. // Call function and display the result
  39. cout << "The string you entered has "
  40. << charCount(input_string)
  41. << " characters.\n";
  42.  
  43. return 0; // Return 0 to indicate successful program termination
  44. }
  45.  
  46. // Function to count the number of characters in a C-string
  47. int charCount(char* ptr) {
  48. int i = 0; // Initialize character count
  49.  
  50. // Loop through each character in the string until
  51. // null terminator is reached
  52. while (*ptr != '\0'){
  53.  
  54. i++; // Increment the counter
  55. ptr++; // Move to the next character
  56.  
  57. }
  58.  
  59. return i; // Return the character count
  60. }
Success #stdin #stdout 0s 5288KB
stdin
thed00odoobird
stdout
Enter a string with a maximum of 20 characters:
I will output the number of characters it has!
The string you entered has 14 characters.