-
vectors of structs
Hey I'm pretty new to C++ but have quite a bit of experience in Java. I have a project to make a Morse code translator. I have a struct that holds a letter and its morse code equivalent. Then I have a vector of these structs to hold all of the combinations. Here's the code thats giving me problems.
Code:
struct Code{
string letter;
string morse;
};
vector<Code>* myConvertorTable;
Code:
void MorseCodeTranslator::setupConvertorTable()
{
ifstream ifstr(myConversionTableFile.c_str());
if(!ifstr)
{
cerr << "Cannot open: " << myConversionTableFile << "." << endl;
exit(ERROR);
}
string tempLetter;
string tempMorse;
while(getline(ifstr, tempLetter))
{
myConvertorTable->letter.push_back(tempLetter);
if(getline(ifstr, tempMorse))
{
myConvertorTable->morse.push_back(tempMorse);
}
}
#ifdef DEBUG
for(int i = 0; i < myConvertorTable->size(); i++)
{
cout << "morse: " << myConvertorTable->morse->at(i) << endl;
cout << "letter: " << myConvertorTable->letter->at(i) << endl;
}
#endif
}
Heres the error messages.
MorseCodeTranslator.cpp: In member function âvoid MorseCodeTranslator::setupConvertorTable()â:
MorseCodeTranslator.cpp:19: error: âclass std::vector<MorseCodeTranslator::Code, std::allocator<MorseCodeTranslator::Code> >â has no member named âletterâ
MorseCodeTranslator.cpp:22: error: âclass std::vector<MorseCodeTranslator::Code, std::allocator<MorseCodeTranslator::Code> >â has no member named âmorseâ
-
The error messages mean exactly what they say: vector<Code> does not, in fact, contain any letters, or any morses. It contains Codes. You need to build a Code and push_back that. You can use a tempCode, just like you're using a templetter and a tempmorse.
-
>> myConvertorTable->morse->at(i)
You've got it backwards. Should be:
myConvertorTable->at(i).morse
-
Thanks the temp struct idea worked.
-
Ignore ME sorry I figured it out.
-
And don't forget to allocate memory for your vector (and free it), since it's a pointer!
But does it really [i]need[I] to be a pointer?