Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Help answering these questions. C++ In regards to the program below. //Code star

ID: 3859203 • Letter: H

Question

Help answering these questions. C++ In regards to the program below.

//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

Explanation / Answer

1. Ans)
In C++ we cannot use cin like below to read a string of words which has spaces in between. Because spaces are considered as terminating string and only you will be able to read first word in a set of words in the string.
e.g: cin >> str
Thats why we need to read an entire line of words using getline statement like below so that it will read your string until it sees a newline(default behaviour).
e.g: getline(cin, str)

2. Ans)
In getline we have another version or overloaded function where we can specify a delimiter so that getline will read until it sees that delimiter. Below is an example program.
In the following example getline will read name of a person until it sees the delimiter '$'.

// Example program
#include <iostream>
#include <string>

int main()
{
std::string name;
std::cout << "What is your name? ";
getline (std::cin, name, '$');
std::cout << "Hello, " << name << "! ";
}

3. Ans)

After we read the string we can remove multiple spaces by matching each character and checking if it is a tab, newline, enter key( ) and space. Then shrinking all of them to a single space. Like in the below code extract of referenced example thats what has been done.

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;
}