Answer:
Explanation:
Section 1) Enter String and Output String
#include<iostream> //for input and output
#include <string> // for string
using namespace std;
int main()
{
string sentense;
cout<<"Enter a sentence or phrase: ";
getline(cin,sentense);
cout<<"You Entered :"<<sentense;
return 0;
}
Output
Enter a sentence or phrase: The only thing we have to fear is fear itself
You Entered :The only thing we have to fear is fear itself
Explanation
To get full sentence or phrase, we need to call getline function in string package which will get the overall entered string. cin will not get the whole sentence
Section 2) GetNumOfCharacters
int getNumberOfCharacters(string sentence){
int count =0;
for(int i=0; i<sentence.size(); i++){
count++;
}
return count;
}
Explanation
As we have taken sentence as string in previous section, we need to count total number of characters in the input string. for that purpose we are iterating over all the characters within string through for loop. declaring count variable and initializing it with 0 and increment on every for loop iteration. at the end returning the count variable.
Section 3) Call the GetNumOfCharacters() in main method.
int main()
{
string sentence;
cout<<"Enter a sentence or phrase: ";
getline(cin,sentence);
cout<< getNumberOfCharacters(sentence); //Here we call out method and output its value
return 0;
}
Explanation
In main method first we get the sentence with getline and then by using cout and calling the getNumberOfCharacters(sentence) function it will show the number of characters in string.
Output
Enter a sentence or phrase: The only thing we have to fear is fear itself
45
Section 4) Implement OutputWithoutWhitespace() function
#include<iostream> //for input and output
#include <string> // for string
using namespace std;
int getNumberOfCharacters(string sentence){
int count =0;
for(int i=0; i<sentence.size(); i++){
count++;
}
return count;
}
void OutputWithoutWhitespace(string sentence){
string output="";
for(int i=0; i<sentence.size(); i++){
if(sentence[i]!=' ' && sentence[i] != '\t'){ // checking the tab and spaces
output+=sentence[i]; //then add that into output string
}
}
cout<< output;
}
int main()
{
string sentence;
cout<<"Enter a sentence or phrase: ";
getline(cin,sentence);
OutputWithoutWhitespace(sentence);
return 0;
}
Code Explanation
In OutputWithoutWhitespace() function we get string as a parameter and iterating all the characters and if current iteration character from sentence string is not equal to tab('\t') and space then add that character into output string. After the loop is finished, output the result.
Output
Enter a sentence or phrase: The only thing we have to fear is fear itself hello
Theonlythingwehavetofearisfearitselfhello