Question

In: Computer Science

C++ I took 7/20 =( code: #include <iostream> #include<string.h> using namespace std; // function to calculate...

C++ I took 7/20 =(

code:

#include <iostream>
#include<string.h>

using namespace std;

// function to calculate number non white space characters
int GetNumOfNonWSCharacters(string str) {
int i = 0;
int count = 0;
while(str[i] != '\0') {
if(str[i] != ' ') {
count += 1;
}
i++;
}
return count;
}

// function to calculate numbers of words
int GetNumOfWords(string str) {
int i = 0;
int count = 1;
while(str[i] != '\0') {
if(str[i] == ' ' && str[i-1] != ' ') {
count += 1;
}
i++;
}
return count;
}


// function to find the number of occurence of the word
int FindText(string word, string str) {
int i = 0;
int count = 0;
while(str[i] != '\0') {
if(str[i] == word[0]) {
int k = i;
int j = 0;
while(word[j] != '\0') {
if(word[j] != str[k]) {
break;
}
if(word[j+1] == '\0') {
count += 1;
}
k++;
j++;
}
}
i++;
}
return count;
}


// function to replace the '!' in string
void ReplaceExclamation(string str) {
int i = 0;
string edited;
while(str[i] != '\0') {
if(str[i] == '!') {
edited[i] = '.';
}
else {
edited[i] = str[i];
}
i++;
}
edited[i] = '\0';

// display resulting string
int j = 0;
cout << "Edited Text:\n" << endl;
while(edited[j] != '\0') {
cout << edited[j];
j++;
}
cout << endl;
}


// function to remove extra spaces
void ShortenSpace(string str) {
int i = 0;
int j = 0;
int len = str.length();
string edited;
while(str[i] != '\0') {
if(str[i] != ' ') {
edited[j] = str[i];
j++;
}
else {
if(edited[j-1] != ' ') {
edited[j] = ' ';
j++;
}

}
i++;
}
edited[j] = '\0';

// display resulting string
int k = 0;
cout << "Edited Text:\n" << endl;
while(edited[k] != '\0') {
cout << edited[k];
k++;
}
cout << endl;
}


// function to display menu options
void PrintMenu(string str) {
while(1) {

// display menu
cout << "MENU" << endl;
cout << "c - Number of non-whitespace characters" << endl;
cout << "w - Number of words" << endl;
cout << "f - Find text" << endl;
cout << "r - Replace all !'s" << endl;
cout << "s - Shorten spaces" << endl;
cout << "q - Quit" << endl;

// read user option
char option;
cout << "Choose an option: ";
cin >> option;
  
// validate input
while(1) {
if(option != 'c' && option != 'w' && option != 'r' && option != 's' && option != 'q' && option != 'f') {
cout << "Choose an option: ";
cin >> option;
}
else{
break;
}
}

// perform the required operation
if(option == 'q') {
break;
}

else if(option == 'c') {
int non_whitespace_chars = GetNumOfNonWSCharacters(str);
cout << "Number of non-whitespace characters: " << non_whitespace_chars << endl;
}

else if(option == 'w') {
int num_words = GetNumOfWords(str);
cout << "Number of words: " << num_words << endl;
}

else if(option == 'f') {
string word;
cin.ignore();
getline(cin, word);
int finds = FindText(word, str);
cout << "Number of words or phrases found: " << finds << endl;
}

else if(option == 'r') {
ReplaceExclamation(str);
}

else {
ShortenSpace(str);
}

cout << endl;
}
}


// main function
int main() {

// read input text and output it
string text;
cout << "Enter sample text:" << endl;
getline(cin, text);
cout << "You entered:\n" << text << endl;

// call print menu function
PrintMenu(text);

return 0;
}

(1) Prompt the user to enter a string of their choosing. Store the text in a string. Output the string. (1 pt)

Ex:

Enter a sample text:
We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!

You entered: We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue!


(2) Implement a PrintMenu() function, which has a string as a parameter, outputs a menu of user options for analyzing/editing the string, and returns the user's entered menu option. Each option is represented by a single character.

If an invalid character is entered, continue to prompt for a valid choice. Hint: Implement Quit before implementing other options. Call PrintMenu() in the main() function. Continue to call PrintMenu() until the user enters q to Quit. (3 pts)

Ex:

MENU
c - Number of non-whitespace characters
w - Number of words
f - Find text
r - Replace all !'s
s - Shorten spaces
q - Quit

Choose an option:


(3) Implement the GetNumOfNonWSCharacters() function. GetNumOfNonWSCharacters() has a constant string as a parameter and returns the number of characters in the string, excluding all whitespace. Call GetNumOfNonWSCharacters() in the PrintMenu() function. (4 pts)

Ex:

Number of non-whitespace characters: 181


(4) Implement the GetNumOfWords() function. GetNumOfWords() has a constant string as a parameter and returns the number of words in the string. Hint: Words end when a space is reached except for the last word in a sentence. Call GetNumOfWords() in the PrintMenu() function. (3 pts)

Ex:

Number of words: 35


(5) Implement the FindText() function, which has two strings as parameters. The first parameter is the text to be found in the user provided sample text, and the second parameter is the user provided sample text. The function returns the number of instances a word or phrase is found in the string. In the PrintMenu() function, prompt the user for a word or phrase to be found and then call FindText() in the PrintMenu() function. Before the prompt, call cin.ignore() to allow the user to input a new string. (3 pts)

Ex:

Enter a word or phrase to be found:
more
"more" instances: 5


(6) Implement the ReplaceExclamation() function. ReplaceExclamation() has a string parameter and updates the string by replacing each '!' character in the string with a '.' character. ReplaceExclamation() DOES NOT output the string. Call ReplaceExclamation() in the PrintMenu() function, and then output the edited string. (3 pts)

Ex.

Edited text: We'll continue our quest in space.  There will be more shuttle flights and more shuttle crews and,  yes,  more volunteers, more civilians,  more teachers in space.  Nothing ends here;  our hopes and our journeys continue.


(7) Implement the ShortenSpace() function. ShortenSpace() has a string parameter and updates the string by replacing all sequences of 2 or more spaces with a single space. ShortenSpace() DOES NOT output the string. Call ShortenSpace() in the PrintMenu() function, and then output the edited string. (3 pt)

Ex:

Edited text: We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes, more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue!

Solutions

Expert Solution

Note:

While executing function for replacing '!' with '.' and shortening the string I have not modified the original string but performed manipulations on a copy of the string.

#include <iostream>
#include <string>


using namespace std;

// function to calculate number non white space characters
int GetNumOfNonWSCharacters(string str)
{
    int i = 0;
    int count = 0;
    while (str[i] != '\0') {
        if (!isspace(str[i])) { //Considers all the non-whitespace charatcers
            count += 1;
        }
        i++;
    }
    return count;
}


// function to calculate numbers of words
int GetNumOfWords(string str)
{
    int i = 0;
    int count = 1;
    while (str[i] != '\0') {
        if (str[i] == ' ' && str[i - 1] != ' ') {
            count += 1;
        }
        i++;
    }
    return count;
}

// function to find the number of occurence of the word
int FindText(string word, string str)
{
    int i = 0;
    int count = 0;
    while (str[i] != '\0') {
        if (str[i] == word[0]) {
            int k = i;
            int j = 0;
            while (word[j] != '\0') {
                if (word[j] != str[k]) {
                    break;
                }
                if (word[j + 1] == '\0') {
                    count += 1;
                }
                k++;
                j++;
            }
        }
        i++;
    }
    return count;
}

// function to replace the '!' in string
void ReplaceExclamation(string str)
{
    int i = 0;
    string edited=str; //First copy the entire contents of the string to new one and then update the new string
    while (str[i] != '\0') {
        if (str[i] == '!') {
            edited[i] = '.';
        }
        else {
            edited[i] = str[i];
        }
        i++;
    }

    // display resulting string
    int j = 0;
    cout << "Edited Text:\n" << endl;
    while (edited[j] != '\0') {
        cout << edited[j];
        j++;
    }
    cout << endl;
}

// function to remove extra spaces
void ShortenSpace(string str)
{
    int i = 0;
    int j = 0;
    int len = str.length();
    bool space=false;
    string edited=str; //Copy entire contents of original string to new one
    while(j < len){
        if(edited[j] != ' '){
            edited[i++]=edited[j++];
            space=false; //no space found thus, setting variable to false
        }
        else if(edited[j++] == ' '){
            if(!space){
                edited[i++]=' '; //Only one space is appended in the string
                space=true;
            }
        }
    }
    edited[i]='\0';

    // display resulting string
    int k = 0;
    cout << "Edited Text:\n" << endl;
    while (edited[k] != '\0') {       //iterate in edited string only till coiunter i as i marks the end of edited string
        cout << edited[k];
        k++;
    }
    cout << endl;
}

// function to display menu options
void PrintMenu(string str)
{
    while (1) {

        // display menu
        cout << "MENU" << endl;
        cout << "c - Number of non-whitespace characters" << endl;
        cout << "w - Number of words" << endl;
        cout << "f - Find text" << endl;
        cout << "r - Replace all !'s" << endl;
        cout << "s - Shorten spaces" << endl;
        cout << "q - Quit" << endl;

        // read user option
        char option;
        cout << "Choose an option: ";
        cin >> option;

        // validate input
        while (1) {
            if (option != 'c' && option != 'w' && option != 'r' && option != 's' && option != 'q' && option != 'f') {
                cout << "Choose an option: ";
                cin >> option;
            }
            else {
                break;
            }
        }

        // perform the required operation
        if (option == 'q') {
            break;
        }

        else if (option == 'c') {
            int non_whitespace_chars = GetNumOfNonWSCharacters(str);
            cout << "Number of non-whitespace characters: " << non_whitespace_chars << endl;
        }

        else if (option == 'w') {
            int num_words = GetNumOfWords(str);
            cout << "Number of words: " << num_words << endl;
        }

        else if (option == 'f') {
            string word;
            cin.ignore();
            getline(cin, word);
            int finds = FindText(word, str);
            cout << "Number of words or phrases found: " << finds << endl;
        }

        else if (option == 'r') {
            ReplaceExclamation(str);
        }

        else {
            ShortenSpace(str);
        }

        cout << endl;
    }
}

// main function
int main()
{

    // read input text and output it
    string text;
    cout << "Enter sample text:\n" << endl;
    getline(file, text);
    cout << "\nYou entered:\n" << text << endl;

    // call print menu function
    PrintMenu(text);

    return 0;
}

Attaching screenshots for the output of the program


Related Solutions

write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char...
write the algorithm for this the code?!. #include<iostream> using namespace std; #include<string.h> int main() { char plain[50], cipher[50]="", decrypt[50]=""; int subkeys[50], len;       cout<<"Enter the plain text:"<<endl; cin>>plain;    cout<<"Enter the first subkey:"<<endl; cin>>subkeys[0];    _strupr(plain);    len = strlen(plain);    /**********Find the subkeys**************/    for(int i=1; i<len; i++) { if ((plain[i-1]>='A') && (plain[i-1]<='Z')) { subkeys[i] = plain[i-1]-65; } }    /****************ENCRYPTION***************/       for(int i=0; i<len; i++) { if ((plain[i]>='A') && (plain[i]<='Z')) {    cipher[i] = (((plain[i]-65)+subkeys[i])%26)+65; }...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating...
Plz convert this C++ code into JAVA code thanks #include<iostream> using namespace std; //function for calculating the average sightings from the Total Sightings array float calcAverage(float totalSightings[],int n) {    int i;    float sum=0.0;    for(i=0;i<n;i++)    sum=sum+totalSightings[i];    return sum/n; } int main() {    // n is no. of bird watchers    //flag , flag2 and flag3 are for validating using while loops    int n,i,flag,flag2,flag3;       //ch also helps in validating    char ch;   ...
Can someone covert the code into C language #include<iostream> #include<iomanip> #include<ios> using namespace std; /******************************************************************************** Function...
Can someone covert the code into C language #include<iostream> #include<iomanip> #include<ios> using namespace std; /******************************************************************************** Function name: main Purpose:                   main function In parameters: b,r,i Out paramters: trun,error,total,value Version:                   1.0 Author: ********************************************************************************/ void main() {    int i;//declaring this variable to get value for quitting or calaculating series    do {//do while loop to calaculate series until user quits        cout << "Enter 1 to evaluate the series." << endl;       ...
I want Algorithim of this c++ code #include<iostream> using namespace std; int main() { char repeat...
I want Algorithim of this c++ code #include<iostream> using namespace std; int main() { char repeat = 'y'; for (;repeat == 'y';){ char emplyeename[35]; float basic_Salary,EPF, Dearness_Allow, tax, Net_Salary , emplyee_id; cout << "Enter Basic Salary : "; cin >> basic_Salary; Dearness_Allow = 0.40 * basic_Salary; switch (01) {case 1: if (basic_Salary <= 2,20,00) EPF = 0; case 2: if (basic_Salary > 28000 && basic_Salary <= 60000) EPF = 0.08*basic_Salary; case 3: if (basic_Salary > 60000 && basic_Salary <= 200000)...
In C++, assuming you have the following incomplete code: #include<iostream> #include <unistd.h> using namespace std; //...
In C++, assuming you have the following incomplete code: #include<iostream> #include <unistd.h> using namespace std; // Structure for storing the process data struct procData { char pname[5]; // Name of a process int arrivt; //Arrival time of a process int pburst; // Burst time of a process int endtime; // Exit time/ Leaving time of a process int remburst; // Remaining burst time of a process int readyFlag; // boolean, Flag for maintaining the process status }; // Global variable...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std;...
Please write variables and program plan(pseudocode) of this C++ programming code: #include <iostream> using namespace std; void leapYear(int x); int main() { int x; cout << "Enter a year: "; cin >> x; leapYear (x);   return 0; } void leapYear(int x ) {    if (x % 400 == 0)    {    cout << "This is a leap Year";}    else if    ((x % 4 == 0) && (x % 100 != 0))    {    cout <<...
Complete the code provided to add the appropriate amount to totalDeposit. #include <iostream> using namespace std;...
Complete the code provided to add the appropriate amount to totalDeposit. #include <iostream> using namespace std; int main() { enum AcceptedCoins {ADD_QUARTER, ADD_DIME, ADD_NICKEL, ADD_UNKNOWN}; AcceptedCoins amountDeposited = ADD_UNKNOWN; int totalDeposit = 0; int usrInput = 0; cout << "Add coin: 0 (add 25), 1 (add 10), 2 (add 5). "; cin >> usrInput; if (usrInput == ADD_QUARTER) { totalDeposit = totalDeposit + 25; } /* Your solution goes here */ else { cout << "Invalid coin selection." << endl;...
What is the flowchart for this code. Thank You! #include<iostream> #include<iomanip> #include<string> #include<cmath> using namespace std;...
What is the flowchart for this code. Thank You! #include<iostream> #include<iomanip> #include<string> #include<cmath> using namespace std; float series(float r[], int n) {    float sum = 0;    int i;    for (i = 0; i < n; i++)        sum += r[i];    return sum; } float parallel(float r[], int n) {    float sum = 0;    int i;    for (i = 0; i < n; i++)        sum = sum + (1 / r[i]);...
Writing a squareroot program in C++ using only: #include <iostream> using namespace std; The program must...
Writing a squareroot program in C++ using only: #include <iostream> using namespace std; The program must be very basic. Please don't use math sqrt. Assume that the user does not input anything less than 0. For example: the integer square root of 16 is 4 because 4 squared is 16. The integer square root of 18 is 5 because 4 squared is 16 and 5 squared is 25, so 18 is bigger than 16 but less than 25.  
C++ please #include <iostream> using namespace std; /** * defining class circle */ class Circle {...
C++ please #include <iostream> using namespace std; /** * defining class circle */ class Circle { //defining public variables public: double pi; double radius; public: //default constructor to initialise variables Circle(){ pi = 3.14159; radius = 0; } Circle(double r){ pi = 3.14159; radius = r; } // defining getter and setters void setRadius(double r){ radius = r; } double getRadius(){ return radius; } // method to get Area double getArea(){ return pi*radius*radius; } }; //main method int main() {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT