So i was working on this assignment, i need to convert normal text into Morse code. We're studying basic c++ at the moment so I'm not allowed to use the string data type or any other complex built-in functions.So I tried doing it through a char array. When i try running it,the following error shows up " ISO C++ forbids converting a string constant to 'char*' "
#include <iostream>
using namespace std;
int len = 0;
char string[45] = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',', '?', '[', '!', '(', ')', '&' };
char* morse[45] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", ".-.-.-", "--..--", "..--..", ".----.", "-.-.--", "-..-.", "-.--.", "-.--.-", ".-..." };
void size(char* arr)
{
for (int i = 0; arr[i] != 0; i++) {
len++;
}
}
int main()
{
char str[100];
cout << "Enter string: ";
cin.getline(str, 100);
size(str);
for (int i = 0; i < len; i++) {
for (int j = 0; j < 45; j++) {
if (str[i] == string[j]) {
cout << morse[j];
break;
}
}
}
return 0;
}
You're defining an array of char*
objects. You initialize those pointers with string literals. But as the error explains, converting a string literal (called constant by the compiler) to char*
is not allowed.
Solution: Converting a string literal to const char*
is allowed, so you could declare an array of const char*
instead. You don't appear to modify the strings pointed by the array, so this shouldn't be a problem.
PS. You've chosen to include a standard library header, and have chosen to use using namespace std;
and defined an identifier with the same name as an identifier declared by the standard library (string
). That will very likely be a problem for the compiler.
Solution: Do not use using namespace std
.
Workaround: Come up with another variable name than string
. The trick is to know all identifiers declared by the standard library. Since this trick isn't trivial and new identifiers will be added in future versions of the standard, I recommend the solution above instead.
The issue, as described in the error, is that "..."
, for example, is a string constant and you are trying to assign to a non-constant char*
. Instead you should be assigning to a const char*
:
const char* morse[45] = { ".-" // ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With