In: Computer Science
Q20. Using C++ style string to write a program that reads a sentence as input and converts each word of the sentence following the rule below:
More requirements:
More assumptions:
Sample Run:
Please enter the original sentence: i LOVE to program Translated: IKPU OVELKPU OTKPU ROGRAMPKPU
Implement the program as follows:
Program:
#include <iostream>
using namespace std;
int main()
{
string sentence, word = "", translated = ""; /* declare string variables */
cout<<"Please enter the original sentence: "; /* ask the user to enter a sentence */
getline(cin, sentence); /* read complete sentence to sentence */
for(int i=0;i<sentence.length();i++){ /* for each character in sentence */
if(sentence[i] == ' '){ /* if character = ' ', it denotes the end of a word */
translated = translated + word.substr (1,string::npos)+ word[0] + "KPU "; /* relocate first character to end, append "KPU" and append it to translated string */
word = ""; /* set word = "" */
}
else{ /* otherwise */
word = word + (char)toupper(sentence[i]); /* convert character to upper-case, cast to character and append it to word */
}
}
translated = translated + word.substr (1,string::npos)+ word[0] + "KPU "; /* for the last word, relocate first character to end, append "KPU" and append it to translated string */
cout<<"\nTranslated: "<<translated; /* print translated string */
return 0;
}
Screenshot:
Output:
Please don't forget to give a Thumbs Up.