Piglatin to English Array allocation to scruture

Write a function that takes in a c++ string of pig latin. This function should first calculate how many “words” are in the sentence (words being substrings separated by whitespace). It should then allocate an array of the structure Word of this size (so large enough to hold the sentence). It should then store each of the words in that sentence to the array of structures in the piglatin field. The function should then return this array to the calling function with a return statement, along with a size through a reference parameter.

note: This function should also remove all capitalization and special characters except for the very end period, exclamation mark or question mark.

My question: I have completed the first part in which I needed to calculate how many words are in the sentence. I am just confused about how to go about allocating an array of the structure Word to hold the sentence, whilst storing it in the piglatin field.

My code this far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <string>
using namespace std;

string piglatin(string);
string english(string);
int countWords(std::string strString);

int main()
{

    int count_words(std::string);

    std::string input_text;
    std::cout<< "Enter a sentence in piglatin: ";
    std::getline(std::cin,input_text);

    std::cout << "Number of words in sentence is: " << count_words(input_text) << std::endl;
  return 0;
}

struct Word 
{
 string piglatin;
 string english;
};

/*string piglatin(string Word)
{
    
    return
}

string english(string Word)
{
    
    return
}*/
int read_input(std::string input_text) 
{
    words = count_words(input_text);
    Word arrayOfWords[words];
    // rest of stuff here
}


int count_words(std::string input_text)
{
    int number_of_words = 1;
    for(int i = 0; i < input_text.length();i++)
        if(input_text[i] == ' ')
            number_of_words++;
    return number_of_words;
}
Last edited on
I am just confused about how to go about allocating an array of the structure Word to hold the sentence, whilst storing it in the piglatin field.


One way to do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Word* read_input (std::string input_text, int &size)
{
  // Get number of words and set it as return value
  size = countWords (input_text);
  
  // allocate array of words 
  Word *Words = new Word[size];
  // fill the array with the words from input_text
  for (int i = 0; i < size; i++)
  {
    Words[i].piglatin = "piglatin"; // words from the input_text
  }

  return Words;
}
Topic archived. No new replies allowed.