fork download
  1. // Diego Martinez CSC5 Chapter 10, P. 591, #14
  2. /*******************************************************************************
  3. * SEPERATE AND DISPLAY WORDS
  4. * ______________________________________________________________________________
  5. * This program accepts a sentence where all words are run together and each
  6. * word begins with an uppercase letter. The program separates the words with
  7. * spaces and converts the sentence so that only the first word begins with
  8. * an uppercase letter.
  9. *
  10. * Example:
  11. *
  12. * Input: StopAndSmellTheRoses
  13. * Output: Stop and smell the roses
  14. *
  15. * ______________________________________________________________________________
  16. * INPUT
  17. *
  18. * A sentence with combined words
  19. *
  20. * OUTPUT
  21. *
  22. * Formatted sentence with spaces
  23. *
  24. *******************************************************************************/
  25.  
  26. #include <iostream>
  27. #include <string>
  28. #include <cctype>
  29. using namespace std;
  30.  
  31. int main()
  32. {
  33. // Variable declarations
  34. string input;
  35. string output = "";
  36.  
  37. // User input
  38. cout << "Enter a sentence: ";
  39. cin >> input;
  40.  
  41. // Process string
  42. for (int i = 0; i < input.length(); i++)
  43. {
  44. // Add space before uppercase letters except first letter
  45. if (isupper(input[i]) && i != 0)
  46. {
  47. output += ' ';
  48. output += tolower(input[i]);
  49. }
  50. else
  51. {
  52. // Keep first letter uppercase, others lowercase
  53. if (i == 0)
  54. {
  55. output += input[i];
  56. }
  57. else
  58. {
  59. output += tolower(input[i]);
  60. }
  61. }
  62. }
  63.  
  64. // Display result
  65. cout << "Formatted sentence: " << output << endl;
  66.  
  67. return 0;
  68. }
Success #stdin #stdout 0.01s 5308KB
stdin
StopAndSmellTheRoses
stdout
Enter a sentence: Formatted sentence: Stop and smell the roses