fork download
  1. //Ryan Shahriyarpour CS1A Chapter 10 Question 14
  2. /*****************************************************************************
  3.  *
  4.  * Word Separator
  5.  *
  6.  *********************
  7.  *
  8.  * This program accepts a sentence in which all of the words are run
  9.  * together, but the first character of each word is uppercase. It converts
  10.  * the sentence to one where the words are separated by spaces and only the
  11.  * first word starts with an uppercase letter.
  12.  * For example, "StopAndSmellTheRoses." becomes "Stop and smell the roses."
  13.  *
  14.  * INPUT
  15.  * sentence - the run-together sentence entered by the user
  16.  *
  17.  * OUTPUT
  18.  * The sentence with spaces between the words
  19.  *
  20.  ****************************************************************************/
  21.  
  22. #include <iostream>
  23. #include <string>
  24. #include <cctype>
  25. using namespace std;
  26.  
  27. // Function prototype
  28. string separateWords(const string &text);
  29.  
  30. int main()
  31. {
  32. // DATA DICTIONARY
  33. // sentence - the run-together sentence entered by the user
  34. // separated - the sentence after the words have been separated
  35. string sentence;
  36. string separated;
  37.  
  38. // Get the sentence
  39. cout << "Enter a sentence with the words run together, each word\n"
  40. << "starting with an uppercase letter: ";
  41. getline(cin, sentence);
  42.  
  43. // Convert and display it
  44. separated = separateWords(sentence);
  45. cout << "\nSeparated: " << separated << endl;
  46.  
  47. return 0;
  48. }
  49.  
  50. // Inserts a space before each uppercase letter (except the first character)
  51. // and converts that letter to lowercase.
  52. string separateWords(const string &text)
  53. {
  54. // DATA DICTIONARY
  55. // result - the converted sentence being built
  56. // index - loop counter
  57. string result;
  58. unsigned int index;
  59.  
  60. for (index = 0; index < text.length(); index++)
  61. {
  62. if (index > 0 && isupper(text[index]))
  63. {
  64. result += ' ';
  65. result += tolower(text[index]);
  66. }
  67. else
  68. result += text[index];
  69. }
  70.  
  71. return result;
  72. }
Success #stdin #stdout 0s 544KB
stdin
ThisIsACodetest
stdout
Enter a sentence with the words run together, each word
starting with an uppercase letter: 
Separated: This is a codetest