fork download
  1. //Sam Partovi CS1A Ch. 10, P.591, #14
  2. /*******************************************************************************
  3. * SEPARATE WORDS WITH SPACES
  4. * ____________________________________________________________
  5. * This program accepts a given string and separates words based on capitalized
  6. * first letters found in the string. The program then displays the separated
  7. * sentence.
  8. * ____________________________________________________________
  9. * INPUT
  10. * userInput : Given string to be separated
  11. * OUTPUT
  12. * stringLength : Length of given string in characters
  13. * formattedString : Separated format of userInput
  14. *******************************************************************************/
  15. #include <iostream>
  16. #include <cstring>
  17. #include <cctype>
  18. using namespace std;
  19.  
  20. int main() {
  21. string userInput; //INPUT - Given string to be separated
  22. int stringLength; //INPUT - Length of given string in characters
  23. string formattedString; //INPUT - Separated format of userInput
  24.  
  25. //Prompt for userInput
  26. cout << "Enter a sentence without spaces: ";
  27. getline(cin, userInput);
  28.  
  29. //Obtain length of given string
  30. stringLength = userInput.length();
  31.  
  32. //Iterate through each character in the string
  33. for(int i = 0; i < stringLength; i++) {
  34.  
  35. //If an uppercase character is found
  36. if(isupper(userInput[i])) {
  37.  
  38. //Insert a space unless first character
  39.  
  40. if(i != 0) formattedString += " ";
  41.  
  42. //Convert character to lowercase
  43. formattedString += (i == 0) ? userInput[i] : tolower(userInput[i]);
  44. }
  45. else formattedString += userInput[i];
  46. }
  47.  
  48. //Display formatted string
  49. cout << "\n" << formattedString;
  50.  
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0.01s 5288KB
stdin
StopAndSmellTheRoses.
stdout
Enter a sentence without spaces: 
Stop and smell the roses.