'Morse Decoder program keep giving unwanted [ instead of English. Why?
I was trying to decode morse code as an assignment, but I somehow am stuck on how this output is always [ instead of the English wordings.
Here are some of the test cases:
Test 1
Input:
._.|.._|_.Output:
RUN
Test 2
Input:
_|....|..|...||..|...||_|....|.||.__|._|_.__Output:
THIS IS THE WAY
Test 3
Input:
...|....|._|_.|_|._|._.|._|__Output:
SHANTARAM
Test 4
Input:
.__.|.|___|.__.|._..|.||..|_.||_|....|.|..|._.||._.|..|__.|....|_||__|..|_.|_..|...||_.|.|..._|.|._.||_|._|_._|.||.__.|._.|..|_..|.||..|_.||_|....|.|..|._.||_|._|._..|.|_.|_|...Output:
PEOPLE IN THEIR RIGHT MINDS NEVER TAKE PRIDE IN THEIR TALENTS
Below is my code.
#include <iostream>
#include <string>
#include <sstream>
/**
* A morse code decoder.
*/
using namespace std;
// IMPORTANT: Do NOT change any of the function headers
// It means that you will need to use the function headers as is
// You may add other functions wherever appropriate
/**
* Decode the morse code `s` and return the text character
*/
string morseCodeToText(string s)
{
string text = "";
string currentLetter = "";
string const morsecode[] = {".-", "-...", "-.-.", "-..", ".", "..-.", //array of alphabet equivalent morse codes
"--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
istringstream ss(s);
size_t const characters = 26;
while(ss >> currentLetter)
{
size_t index = 0;
while(currentLetter != morsecode[index] && index < characters)
{
++index; //increment here so we don't have to decrement after the loop like if we put in the condition
}
text += 'A' + index;
}
return text;
}
int main()
{
string s;
cin >> s;
cout << morseCodeToText(s) << '\n';
return 0;
}
Solution 1:[1]
while(ss >> currentLetter)
Here you're reading your input until a newline is found. You want to read until a | is meet.
For that, you can simply rely on std::getline() (see delim):
while(std::getline(ss, currentLetter, '|'))
Why [ though?
currentLetter != morsecode[index]
You're comparison is always false. This makes index be 26 when the inner while loop ends. This leads to:
text += 'A' + index; // 65 + 26 = 91 '['
test being always one-past-Z, which is [ in ASCII.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | YSC |
