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

USE C-Style String in C++ In your main routine, read strings from cin to build o

ID: 3872035 • Letter: U

Question

USE C-Style String in C++

In your main routine, read strings from cin to build one large string containing all the entered words. Make sure to add a space between each word in the string. Use an appropriate string function to obtain the characters of the string as a char array until user enter "stop", Print your result(the string entered but "stop" exclusive ) to cout to verify.

Define a function mean returning a double and taking a pointer to char as argument. Use const as you see fit. The function should calculate the mean ASCII value of the word at the location pointed to. A word is defined here as all the characters until an empty space or until the end of the string is encountered, whatever comes first.

Explanation / Answer

#include<iostream>
#include<malloc.h>
#include<string.h>
using namespace std;
double mean(char *ptr)
{
    int i=0;int sum=0;
    while(ptr[i]!=' ' && ptr[i]!='')// while a space or null is not encountered
    {
       sum+=*(ptr + i++);//keep adding the ascii value at i to sum

    }
    return (double) sum/i;// return average of ascii values
}
int main()
{
    char *word = (char*)malloc(sizeof(cin>>word));
    char *sentence = (char*)malloc(0);//allocate initial memory to sentence

    while(strcmp(word,"stop")!=0)
    {

        cin>>word;
        if(strcmp(word,"stop")!=0)
        {
            realloc(sentence,strlen(sentence)+strlen(word));//reallocate memory to sentence
            strcat(sentence,word);//use strcat to combine the last word with the sentence
            strcat(sentence," ");// for space between two words
        }
    }
    cout<<sentence<<endl;//display sentence
    char a[]="bhai ";
   double avg= mean(a);
   cout<<avg;


return 0;
}