Reputation: 1
I need to convert English letters and Arabic numbers to Morse code until enter
is pressed. I used a do while
loop to read letters until enter
is pressed.
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int j = 0;
char a[100];
const char *latin = "**ETIANMSURWDKGOHVF?L?PJBHCYZQ??54?3??2?????6????7??890";
void dash(){cout<<"-";}
void dot(){cout<<".";}
void conv(int decimal)
{
if(decimal){
conv(decimal/2);
if(decimal!=1) decimal%2 ? dash() : dot();
}
}
void morse(char a[], int lenght)
{
for(int i = 0; i <= lenght; i++)
{
if(a[i] >= 'a' && a[i] <= 'z') a[i] -= 32;
if(a[i] < 'A' && a[i] > 'Z') return;
while(latin[++j] != a[i]);
conv(j);
}
}
int main()
{
int lenght = 0;
cout<<"letter=";
do{
cin>>a[lenght];
lenght++;
} while(0);
morse(a, lenght);
return 0;
}
When I return the length it is always one, so the function makes only one loop. Also, there are some extra symbols that appear when the code is compiled.
Upvotes: 0
Views: 574
Reputation: 958
There are a few things going on here, but the reason that lenght
is always 1
is because you only run through your while loop once:
do {
cin>>a[lenght];
lenght++;
} while (0); // this will always evaluate to false
The do
block above only executes once because while (0)
evaluates to false. This means that lenght
is only incremented once, which would explain why its value is 1
.
Here's a (potentially) better way:
while (cin.peek() != '\n') {
cin >> a[lenght++];
}
And you can get the output you're looking for by modifying main()
:
int main()
{
int length = 0;
cout << "letter = ";
while (cin.peek() != '\n') {
cin >> a[length++];
}
int i = 0;
while (i < length) {
morse(a[i]);
i++;
}
cout << endl;
return 0;
}
Code
Here it is all assembled (along with a few minor changes to conv()
and morse()
):
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int j = 0;
char a[100];
const char *latin = "**ETIANMSURWDKGOHVF?L?PJBHCYZQ??54?3??2?????6????7??890";
void dash(){cout<<"-";}
void dot(){cout<<".";}
void conv(int decimal) {
if (decimal) {
conv(decimal/2);
if (decimal != 1) decimal%2 ? dash() : dot();
}
}
void morse(char c) {
if (c >= 'a' && c <= 'z') c -= 32;
if (c < 'A' || c > 'Z') return;
int i = 0;
while (latin[++i] != c);
conv(i);
}
int main()
{
int length = 0;
cout << "letter = ";
while (cin.peek() != '\n') {
cin >> a[length++];
}
int i = 0;
while (i < length) {
morse(a[i]);
i++;
}
cout << endl;
return 0;
}
Input
$ letter = sos
Output
$ ...---...
Edit
As pointed out by user4581301 below, this can be simplified further by removing a[] and the second loop:
int main()
{
int length = 0;
char c;
cout << "letter = ";
while (cin.peek() != '\n') {
char c;
cin >> c;
morse(c);
}
cout << endl;
return 0;
}
Upvotes: 2