fork download
  1. // Timothy Price CS1A Ch 10 Challenge 1
  2. /******************************************************************************
  3.  * Calulate number of characters
  4.  *
  5.  * This program receives a set of characters and counts them.
  6.  *
  7.  * Input:
  8.  * a word or a set of characters
  9.  *
  10.  * Output:
  11.  * the number of characters
  12. ******************************************************************************/
  13.  
  14. #include <iostream>
  15.  
  16. using namespace std;
  17.  
  18. // Function prototype
  19. int countCharacters(const char* str);
  20.  
  21. int main()
  22. {
  23.  
  24. // Data dictionary
  25. const int MAX_LENGTH = 256;
  26. char input[MAX_LENGTH];
  27. int charCount;
  28.  
  29. // Receive input and give confirmation
  30. cout << "Enter a string: ";
  31. cin.getline(input, MAX_LENGTH);
  32. cout << input << endl;
  33.  
  34. // Call function
  35. charCount = countCharacters(input);
  36.  
  37. // Output resulting character count
  38. cout << "Character count: " << charCount << endl;
  39.  
  40. return 0;
  41. }
  42.  
  43. // Function definition
  44. int countCharacters(const char* str)
  45. {
  46. // Initialize counter
  47. int count = 0;
  48.  
  49. // Loop to increase counter until null terminator is met
  50. if (str != nullptr)
  51. {
  52. while (*str != '\0')
  53. {
  54. count++;
  55. str++;
  56. }
  57. }
  58.  
  59. return count;
  60. }
Success #stdin #stdout 0s 544KB
stdin
Pneumonoultramicroscopicsilicovolcanoconiosis
stdout
Enter a string: Pneumonoultramicroscopicsilicovolcanoconiosis
Character count: 45