#include <iostream>
#include <string.h>
#include <conio.h>
using namespace std;
int main()
{
char option;
int choice;
string str;
string text[39] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","STOP",",","?"};
string morse[39] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.",
"--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",".----","..---","...--","....-",
".....","-....","--...","---..","----.","-----",".-.-.-","--..--","..--.."};
do{
system("cls");
cout << "1. Encode(Text to Morse)\n";
cout << "2. Decode(Morse Code to Text)\n";
cout << "3. Display the Morse Code\n";
cout << "4. Quit\n";
cout << "\nEnter a number 1-4: ";
cin >> choice;
switch(choice)
{
case 1:
{
cout << "Enter text: ";
cin.ignore();
getline(cin,str);
cout << "\n";
cout << "The target string to be translated is:";
cout << str;
cout << "\n\nNumber of characters in the string is "<<str.length();
cout << "\nIn Morse the message is:\n";
int i; //string position counter
int a; //morse code finder loop counter
i = 0;
while (i<str.length()) //to loop every single position in the string.
{
a = 0;
if((str[i] >= 'a') && (str[i] <= 'z')) // upcase everything
str[i] = toupper(str[i]);
string n = "";
n += str[i]; // convert str[i] (a char) to string.
while ( a<= 39 ) // to find the matching morse code to that character.
{
if (n == text[a])
{
cout << morse[a] << " ";
}
a += 1;
}
if(str[i] == ' ')
cout << "\n";
i += 1;
}
cout << "Run this again?(y/n)\n";
cin >> option;
}
break;
default:
}
}while((option == 'y')||(option=='Y'));
}
我还没有完成剩下的工作,但这部分一直在崩溃。我认为循环有问题。 我无法弄清楚哪个部分出了问题.. xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
答案 0 :(得分:2)
你的问题在这里:
a<= 39
数组的大小为39,因此索引39超出范围。
应该是:
a < 39