Walter
Walter

Reputation: 125

Problems array and char

I'm new to programming. I can't find errors in this code. I'm trying to translate some characters to numbers.

The program ask to enter a message, but after I entered the characters nothing show up.

#include <stdio.h>
#define N 100

int main (void)
{
    char message[N];
    int i;
    printf ("Enter a message: ");

    for (i=0; i<N; i++){
        scanf ("%c", &message[i]);
    }
    // characters are in the array

    for (i=0; i<N; i++){
        if (message[i]=='a')
            message[i]='4';
        if (message[i]=='b')
            message[i]='8';
        if (message[i]=='e')
            message[i]='3';
        if (message[i]=='i')
            message[i]='1';
        if (message[i]=='o')
            message[i]='0';
        if (message[i]=='s')
            message[i]='5';
    }
    // characters are translated

    for (i=0; i<N; i++)
        printf ("%c ", message[i]);
    // characters are printed

    return 0;
}

Upvotes: 0

Views: 78

Answers (2)

Quan Vo
Quan Vo

Reputation: 1336

What compiler do you use? Your code works well in https://www.jdoodle.com/c-online-compiler. For this case, if I understand exactly, you can better get a complete message, use:

scanf("%s", message);

instead of:

for (i=0; i<N; i++){
scanf ("%c", &message[i]);
}

Upvotes: 0

user2736738
user2736738

Reputation: 30936

You can simply read the whole message by using scanf("%s",message);

That way you don't have to wait for all the 100 characters to be entered and you can check with whatever input (maybe less than 100 characters) you have given. Same way you can print it using printf

printf("%s",message);

Use switch for doing the characters change based on different cases.

switch(message[i]){
   case 'a': message[i]='4';break;
   ...
}

Instead of looping for all N characters loop till strlen(message) or message[i]!='\0'

Upvotes: 1

Related Questions