My program compiles fine, but when it runs it will give me a segmentation fault.
I have tried to get it to collect the strings for the message1 vector, but I can't seem to get it to work. I think that's where the problem is. Any ideas? Also I put in bold where I think the error may be in.
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Code
{
public:
Code(); // Default constructor - loads and uses morse code
string decode(vector< string> message); // decodes a message
private:
vector<string> codewords; // this is a codeword vector parallel to A-Z
vector<char> alpha; // this is the vector for A-Z
vector<char> alphacode(); // function builds the vector alpha - A B C etc.
vector<string> morsecode(); // function builds the vector codewords containing morse code
char decode(string c); //returns the character for the codeword c.
You never declare the variable 'i' in main().
You also declare the variable 'message1' in main() but then refer to it as 'message', meaning that you have yet another undeclared variable being referenced in main().
string Code::decode(vector<string> message)
{
string temp;
for (int i = 0; i < message.size(); i++)
{
temp += decode(message[i]);
}
}
This function is supposed to return a string and doesn't.
1 2 3 4 5 6 7 8 9 10 11
char Code::decode (string c)
{
for (int i = 0; i < codewords.size(); i++)
{
if (c == codewords[i])
{
return alpha[i];
}
}
return 0; // A failure value of some kind.
}
This function needs to return something even if it can't find it. Return a default value outside the loop if you have to, or a failure, just return *something*. You can't not return anything.
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
vector<string> message1(26);
while (cin.good())
{
for(int i=0; i < 26; i++)
{
cin >> message1[i]; //Was message1(i) before.
}
}
Code morse;
cout << morse.decode(message1);
}
To access the elements of a vector you should either access it as an array, with square brackets, or you could use the function "at", e.g. "message1.at(i);"
I would very, very, very highly recommend you learn to read compiler errors, and interpret them accordingly. All of this information I gleaned by just trying to compile your code in VC++ 2010 and reading the errors it gave me. This is an absolutely crucial skill for any coder, and I would highly recommend you try to cultivate it.
Also, re: the above: Declaring a variable inside the for loop as he did is technically valid, so that was not the problem in this case. Either way works though.