0

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;
}
5
  • To start with, scanf ("%c", &message[i]); --> scanf (" %c", &message[i]); Commented Nov 8, 2017 at 11:47
  • 2
    Your program isn't going to do anything until you enter 100 characters. Is that the intent? Commented Nov 8, 2017 at 11:48
  • Try this : ide.geeksforgeeks.org/J0LvwM Commented Nov 8, 2017 at 11:54
  • if(message[i] == '\n') break; Commented Nov 8, 2017 at 12:03
  • Welcome to Stack Overflow! Please edit your question to show us what kind of debugging you've done. I expect you to have run your minimal reproducible example within Valgrind or a similar checker, and to have investigated with a debugger such as GDB, for example. Ensure you've enabled a full set of compiler warnings, too. What did the tools tell you, and what information are they missing? And read Eric Lippert's How to debug small programs. Commented Nov 8, 2017 at 16:14

2 Answers 2

1

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'

Sign up to request clarification or add additional context in comments.

Comments

0

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.