C++ Help program this? Write a program that reads in a sentence from the user. B
ID: 3859161 • Letter: C
Question
C++ Help program this?
Write a program that reads in a sentence from the user. But wait! That's not all it must do! Your program should output the sentence with spacing corrected and with letters corrected for capitalization. In terms of spacing correctness, the output sentence should have all sequences of two or more blanks compressed to a single space - unless there were blanks at the beginning of the sentence. Blanks at the beginning of a sentence should be obliterated utterly! (Blank here can mean any type of spacing - space, tab, new-line, ...) The sentence should Start with an uppercase letter but should contain no other uppercase letters. (Do not worry about proper names: if their first letters are changed to lowercase, that's acceptable.) For simplicity, you may assume that the user's sentence ends in a period and contains no other periods (i.e. no abbreviations or such). $ sentence.out Welcome to the Style Stabilizing Program! Please enter your sentence (end with a period): the Answer to life, the Universe, and everything IS 42, Corrected, your sentence is: The answer to life, the universe, and everything is 42. Thanks for stabilizing your style with us today! Try to have a punctual day here-after! $Explanation / Answer
Hey,
I have provided the code below. Comment if you have any queries. Also give a thubs up if this answer helped you.
//Code starts here
#include <iostream>
#include <cstring>
using namespace std;
int remove_whitespaces(char *p)
{
int len = strlen(p);
int new_len = 0;
bool space = false;
for (int i = 0; i < len; i++)
{
switch (p[i])
{
case ' ': space = true; break;
case ' ': space = true; break;
case ' ': space = true; break;
case ' ': space = true; break;
default:
if (space && new_len > 0)
p[new_len++] = ' ';
p[new_len++] = p[i];
space = false;
}
}
p[new_len] = '';
return new_len;
}
inline int remove_whitespaces(std::string &str)
{
int len = remove_whitespaces(&str[0]);
str.resize(len);
return len;
}
int main()
{
std::string x;
std::cout << "Please Enter your sentence" << endl;
std::getline(std::cin, x);
remove_whitespaces(x);
x[0] = std::toupper( x[0] );
for( std::size_t i = 1 ; i < x.length() ; ++i )
x[i] = std::tolower( x[i] );
cout << "Corrected, your sentence is" << endl;
cout << x << endl;
return 0;
}
//Code ends here
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.