n-2r7
n-2r7

Reputation: 331

Translating Program

I am beginning to write a translator program which will translate a string of text found on a file using parallel arrays. The language to translate is pig Latin. I created a text file to use as a pig latin to English dictionary. I didn't want to use any two dimension arrays; I want to keep the arrays in one dimension. Basically I want to read a text file written in PigLatin and using the dictionary I created I want to output the translation to English on the command line.

My pseudo-code idea is:

I was thinking on using a parallel arrays, one containing the english translated words and another one containing the pig latin words.

I would like to know how can I manipulate the strings using arrays in C++?

Thank you.

Upvotes: 1

Views: 5519

Answers (3)

Rob Kennedy
Rob Kennedy

Reputation: 163317

Declaring an array of strings is easy, the same as declaring an array of anything else.

const int MaxWords = 100;
std::string piglatin[MaxWords];

That's an array of 100 string objects, and the array is named piglatin. The strings start out empty. You can fill the array like this:

int numWords = 0;
std::ifstream input("piglatin.txt");
std::string line;
while (std::getline(input, line) && numWords < MaxWords) {
  piglatin[numWords] = line;
  ++numWords;
}
if (numWords == MaxWords) {
  std::cerr << "Too many words" << std::endl;
}

I strongly recommend you not use an array. Use a container object, such as std::vector or std::deque, instead. That way, you can load the contents of the files without knowing in advance how big the files are. With the example declaration above, you need to make sure you don't have more than 100 entries in your file, and if there are fewer than 100, then you need to keep track of how many entries in your array are valid.

std::vector<std::string> piglatin;

std::ifstream input("piglatin.txt");
std::string line;
while (std::getline(input, line)) {
  piglatin.push_back(line);
}

Upvotes: 1

Aleksei Potov
Aleksei Potov

Reputation: 1578

If files will be always translated in one direction (e.g. PigLatin -> English) then it would be easier and more efficient to use std::map to map one string to another:

std::map<std::string, std::string> dictionary;
dictionary["ashtray"] = "trash";
dictionary["underplay"] = "plunder";

And get translated word, just use dictionary[] to lookup (e.g. std::cout << dictionary["upidstay"] << std::endl;)

Upvotes: 5

pbos
pbos

Reputation: 476

Pig latin can be translated on the fly.

Just split the words before the first vowel of each word and you won't need a dictionary file. Then concatenate the second part with the first part, delimited with a '-', and add "ay" at the end.

Unless you want to use a dictionary file?

Upvotes: 4

Related Questions