所以這個背後的想法是,用戶輸入一條消息,並將消息轉換爲莫爾斯碼。這是我在今天工作了8個多小時的家庭作業。這也是我第一次認真對待課堂。比較兩個向量可能會給我一個錯誤
運行時,我在64行只有一個錯誤。我得到的錯誤沒有意義(它是huuuuge所以我不想包括它,除非問)。我懷疑問題是原始消息矢量和alphaCode矢量是不同的矢量類型(字符串分別爲& char)。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Code
{
private:
vector<char> alphaCode;
vector<string> morseCode;
vector<string> originalMessage;
vector<string> finalMessage;
public:
Code();
void encoder(vector<string> input);
void display();
};
Code::Code():alphaCode(), morseCode(28)
{
//Building alphaCode
for (char c='A'; c<='Z'; c++) alphaCode.push_back(c);
alphaCode.push_back(' ');
alphaCode.push_back('.');
//Building morseCode
morseCode[0] =".-";
morseCode[1] ="-...";
morseCode[2] ="-.-.";
morseCode[3] ="-..";
morseCode[4] =".";
morseCode[5] ="..-.";
morseCode[6] ="--.";
morseCode[7] ="....";
morseCode[8] ="..";
morseCode[9] =".---";
morseCode[10] ="-.-";
morseCode[11] =".-..";
morseCode[12] ="--";
morseCode[13] ="-.";
morseCode[14] ="---";
morseCode[15] =".--.";
morseCode[16] ="--.--";
morseCode[17] =".-.";
morseCode[18] ="...";
morseCode[19] ="-";
morseCode[20] ="..-";
morseCode[21] ="...-";
morseCode[22] =".--";
morseCode[23] ="-..-";
morseCode[24] ="-.--";
morseCode[25] ="--..";
morseCode[26] =".......";
morseCode[27] ="x";
}
void Code::encoder(vector<string> input)
{
originalMessage = input;
for (int i = 0; i < originalMessage.size(); i++)
{
for (int j = 0; j < alphaCode.size(); j++)
{
if (originalMessage[i] == alphaCode[j])
{
finalMessage.push_back(morseCode[j]);
finalMessage.push_back(" ");
}
}
}
}
void Code::display()
{
for (int x; x < finalMessage.size(); x++) cout << finalMessage[x];
}
//------------------------------------------------------------------------------
int main()
{
vector<string> message;
string temp;
cout << "Input:" << endl;
cin >> temp;
message.push_back(temp);
Code c1;
c1.encoder(message);
c1.display();
}
你想通弄明白了。什麼是問題?您正在混合類型並將整個字符串與字符進行比較。這在C++中是沒有意義的。 – luk32
對不起,我還是個新手。基本上這是這項任務:http://cse.csusb.edu/murphy/cse202/hw2-2014.html 這是一個有點沉重。 –
@SriniKumar - FWIW,解決這個問題的更好方法是使用'std :: map'或查找表。不知道爲什麼comp sci當然會告訴你解決這個問題的最糟糕的方法,通過線性搜索直到找到正確的代碼。 – PaulMcKenzie