#include <iostream>
#include <limits>
int main () {
char nums[10][5] = {'.'};
int u_input = 0;
for (int i = 0; i < 10; ++i) {
if (i < 5) {
for (int d = 0; d <= i; ++d)
nums [i][d] += '.';
for (int ds = (i + 1); ds < 5; ++ds)
nums [i][ds] = '-';
continue;
}
if (i >= 5) {
for (int ds = 0; ds < (i - 4); ++ds)
nums [i][ds] += '-';
for (int d = (i - 4); i < 5; ++d)
nums [i][d] += '.';
}
}
do {
std::cout << "Convert number from 0 to 9 into morse (-1 to exit): ";
std::cin >> u_input;
if (u_input > 0) {
if (u_input <= 9) {
for (int d = 0; d < 5; ++d)
std::cout << nums [u_input - 1][d];
}
}
elseif (u_input == 0) {
for (int d = 0; d < 5; ++d)
std::cout << nums [9][d];
}
std::cout << std::endl;
} while (u_input != -1);
std::cout << "Thanks for using this program" << std::endl;
std::cout << "Press any key to continue...";
std::cin.ignore (std::numeric_limits<int>::max(), '\n');
std::cin.get();
return 0;
}
my results is:
* when i entered 1 the result is \---- while if i entered number between 2 to 5 it displayed the correct results
* when i submit 6 to 9 it displayed only the dashes (without the dots)
At line 5, you initialize your array to dots (decimal value 46).
At line 11, you add the decimal value of two dots together. This gives you a decimal value of 92, which is a backslash.
Why are you trying to construct the Morse strings dynamically? Yes, you can do that for numbers, but if you're going to extend your program to handle letters, that is not going to work.
As jlb suggested, using a std::map will allow you to use both alpha and numbers.
A much simpler approach for handling just numbers is to use an array of strings.
bro, for real? seriously? using strings is too simple... if that's the answer, i knew it already
the purpose i'm using it because i wanna find the algorithm of converting nums to morse... because there's a pattern for nums...
if (i >= 5) {
for (int ds = 0; ds < (i - 4); ++ds)
nums [i][ds] = '-';
//for (int d = (i - 4); i < 5; ++d) was testing against i for termination!
for (int d = (i - 4); d < 5; ++d) // now testing against d
nums [i][d] = '.';
}
Andy
PS Your for first for-loop can be simplified a bit, too, if you use an else
1 2 3 4 5 6 7 8 9 10 11 12 13
for (int i = 0; i < 10; ++i) {
if (i < 5) {
for (int d = 0; d <= i; ++d)
nums [i][d] = '.';
for (int ds = (i + 1); ds < 5; ++ds)
nums [i][ds] = '-';
} else {
for (int ds = 0; ds < (i - 4); ++ds)
nums [i][ds] = '-';
for (int d = (i - 4); d < 5; ++d)
nums [i][d] = '.';
}
}
@andy: thank you so much!!! i've been staring the code tens of times (and probably i even dream about it, and of course, it would be a nightmare) and i can't figure out the error!!!