0

I wrote a program that translates a sentence into B1FF language. When i enter a message and hit enter, it doesn't give any output, using a specific piece of code. I can make it work when i write the code in a specific way but i choose to write it in another way, which should be similar. Can you explain why it doesn't work?

This piece of code works for my program and i thought it was similar to the other code:

for(;(message[len] = getchar()) != '\n';) len++;

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define N 50

int main() {
char message[N];
int len=0;
printf("Enter message: ");
/*this is the part that is not working and i have no idea why. I 
  thought it's similar to the other code i provided*/
do {
    message[len] = getchar();
    len++;
} while (message[len] != '\n');

for(int i = 0; i < len; i++) {
    switch(toupper(message[i])) {
        case 'A': putchar('4'); break;
        case 'B': putchar('8'); break;
        case 'E': putchar('3'); break;
        case 'I': putchar('1'); break;
        case 'O': putchar('0'); break;
        case 'S': putchar('5'); break;

        default: putchar(toupper(message[i])); break;
    }
}
printf("!!!!!!!!!!");
return 0;

}

Yaim
  • 27
  • 5

1 Answers1

0

Few observations about the sample code. Here

len++;
message[len] != '\n' /* at this stage message[len] contains Garbage not the valid char due to len++ */

len gets incremented before message[len] != '\n' statement and then accessing len+1 characters of array causes undefined behavior. To avoid this you can check like

message[len-1] != '\n'

Next, message array is not null terminated. After coming out from loop end the array with '\0'. For e.g

message[len] = '\0';

Best way is to initialize char array while declaring itself. For e.g

char message[50] = {}; /* zeroed the whole array */
Achal
  • 11,821
  • 2
  • 15
  • 37
  • 1
    Null termination in the given code is not necessary as the array is not treated as string anyway. – Eugene Sh. Jul 19 '19 at 16:15
  • 1
    Empty initializer is not standard https://stackoverflow.com/questions/17589533/is-an-empty-initializer-list-valid-c-code – Eugene Sh. Jul 19 '19 at 16:25