2015-02-19 5 views
0

Я пишу программу, которая будет вводить буквенное сообщение, и использовать класс для построения строки кода Морзе, а затем вывести строку. Я написал весь метод, и программа компилируется в порядке. Однако, когда я ввожу строку temp и нажимаю return. Мне дается ошибка сегментации. Кажется, я не могу найти проблему. Если кто-нибудь может понять, в чем проблема, я бы очень признателен за вашу помощь. Благодарю.Ошибка сегментации строк чтения С ++

#include <string> 
#include <vector> 
#include <fstream> 

using namespace std; 

class Code 
{ 
public: 
    Code(); // Default constructor - loads and uses morse code 
    string decode(vector< string> message); // decodes a message 
    string encode(vector<char> message); // encodes 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. 
    string encode(char c); 
}; 

Code::Code() { 
    alpha = alphacode(); 
    codewords = morsecode(); 
} 

string Code::decode(vector< string> message) { 
    string temp; 
    for (int i=0; i < message.size(); i++) { 
     temp += decode(message[i]); 
    } 
    return temp; 
} 


string Code::encode(vector<char> message) 
{ 
    string temp; 
    for (int i=0; i<message.size(); i++) 
    { 
     temp+=encode(message[i]); 
    } 
    return temp; 
} 

vector<string> Code::morsecode() 
{ // This function returns a vector containing the morse code 
vector<string> temp(28); 
temp[0] =".-"; 
temp[1] ="-..."; 
temp[2] ="-.-."; 
temp[3] ="-.."; 
temp[4] ="."; 
temp[5] ="..-."; 
temp[6] ="--."; 
temp[7] ="...."; 
temp[8] =".."; 
temp[9] =".---"; 
temp[10] ="-.-"; 
temp[11] =".-.."; 
temp[12] ="--"; 
temp[13] ="-."; 
temp[14] ="---"; 
temp[15] =".--."; 
temp[16] ="--.--"; 
temp[17] =".-."; 
temp[18] ="..."; 
temp[19] ="-"; 
temp[20] ="..-"; 
temp[21] ="...-"; 
temp[22] =".--"; 
temp[23] ="-..-"; 
temp[24] ="-.--"; 
temp[25] ="--.."; 
temp[26] ="......."; 
temp[27] ="x"; 
return temp; 
} 

vector<char> Code::alphacode() 
{// This returns a vector containing the alphabet a-z and " " 
vector<char> temp; 
for (char c='A'; c<='Z'; c++) 
     temp.push_back(c); 
temp.push_back(' '); 
temp.push_back('.'); 
return temp; 
} 

char Code::decode(string c) 
{ 
    for (int i = 0; i < alpha.size(); i++) { 
     if(c == codewords[i]) { 
      return alpha[i]; 
     }  
    } 
} 

string Code::encode(char c) 
{ 
    for (int i=0;i<codewords.size();i++) 
    { 
     if (c==alpha[i])     
     { 
      return codewords[i];      
     } 
    } 
} 
int main() 
{ 

vector<char> message; 
    string temp; 

    getline(cin, temp); 
     for (int i=0; i <temp.length(); i++) 
     { 
      message.push_back(temp[i]); 
     } 

    Code C; 
    cout << C.encode(message) << endl; 
} 

ответ

1

Ваши алфавиты и мрэккоды предназначены только для прописных букв, поэтому эта функция возвращает значение null, что приводит к проблемам.

string Code::encode(char c) 
{ 
    for (int i=0;i<codewords.size();i++) 
    { 
     if (c==alpha[i])     
     { 
      return codewords[i];      
     } 
    } 
} 

Ваш чек на c==alpha[i] следует либо проверить игнорируя регистр или ваши альфа-коды должны иметь небольшие коды алфавита, а также. У ваших мнений также должны быть коды для маленьких алфавитов, а ваши чеки, где вы указываете A-Z до 0-28, должны содержать небольшие буквы.

Помните, что маленькие буквы имеют разные коды ASCII, кроме прописных букв.

0

Следующая функция не имеет оператора возврата в конце.

string Code::encode(char c) 
{ 
    for (int i=0;i<codewords.size();i++) 
    { 
     if (c==alpha[i])     
     { 
      return codewords[i];      
     } 
    } 

    // What should happen if execution gets to this line? 
} 

Если за шанс, что ваш код достигает конца функции, вы будете работать в неопределенное поведение. Это может быть источником вашей проблемы.