-4

I have to convert a capitalized character to its NATO phonetic alphabet counterpart. Using two arrays.

letters.txt is a text file with letters A-Z

words.txt is a text file with the NATO phonetic alphabet Alpha-Zulu

(Ex: A=Alpha, B=Bravo...)

The problem I have is that every time a letter is converted only Zulu is printed.

What do I have to add or change to this program so it can convert correctly?

Here is the code

 #include <iostream>
 #include <string>
 #include <fstream>
 #include <iomanip>
 using namespace std;

 int main()
{

ifstream inputFile;
inputFile.open("words.txt");
string word;

while (inputFile >> word)
{
}


inputFile.open("letters.txt");
char letter;

while (inputFile >> letter)
{
}

char choice;
char letter2;
char Alpha[26]={letter};
string Words[26]={word};
    do
{

    cout<<"\nPlease enter a letter"<<endl;
    cout<<"Letter: ";
    cin>>letter2;

for(int count=0; count < 26; count++)
    {

    cout<< Words[count];

    }

    cout<<"\nDo you want to run this program again? <y/n>"<<endl;
    cin>>choice;

}
    while(choice=='y' || choice=='Y');

return 0;
}
  • 1
    `while (inputFile >> word){}` will simply replace the previous `word` each iteration. You only store one word, the last read. `string Words[26]={word};` defines an array of 26 `string`, the first word is whatever is stored in `word` and the rest are empty strings. Read directly into `Words` and `Letters`. – François Andrieux Apr 18 '17 at 17:12

1 Answers1

2

You need proper containers to hold your letters and words.

Right now you are reading them from files, putting every word/letter into a variable (variables named word and letter). But every word/letter overwrites the previous one (that's why your are seeing only the last word, Zulu).

To actually read and hold them all you need a vector or array.

Example for words (do the same for letters):

std::vector<std::string> words;
words.reserve(26); // you know you need 26 words, reserve memory in advance
string word;

while (inputFile >> word)
{
  words.push_back(word);
}

Like this all your words are into your container words.

Then continue your algo ;-)

Ðаn
  • 10,934
  • 11
  • 59
  • 95