C program to replace char's

Started by
2 comments, last by the_edd 13 years, 6 months ago
Ok I am trying to make a simple program to "encode" a message that is given by the user. The encoding scheme is very simple (for now) all it does it change the char to the next char in the alphabet. EX: input is abc, output should be bcd.

if i do this, the character replacement works: it will replace everything with *'s

#include <stdio.h>#include <stdlib.h>#include <ctype.h>char encode(char ch);int main(){     char ch;            while (ch = getchar() != EOF)     {          ch = encode(ch);          putchar(ch);     }          system("pause");     return 0;}char encode(char ch){     ch = '*';     return ch;}


however if i surround the "ch = '*'; part with a check to only do it if it is a alphabetic character it does not work outputs just some funky smiley face character.

char encode(char ch){     if (isalpha(ch))     {          ch = '*';     }     return ch;}


also another question, how would i go about making the value of ch be the next letter from what ch currently is.
Advertisement
while (ch = getchar() != EOF)


The above code is equivalent to:
while( ch = (getchar() != EOF) )


If getchar() != EOF, then ch is assigned to 1, which is the funky smiley face character you were referring to.

Did you mean? :
while ( (ch = getchar()) != EOF)


Quote:Original post by EvilCloneVlad
also another question, how would i go about making the value of ch be the next letter from what ch currently is.


Remember that char is an integral type; you can treat it as if it were regular int. Therefore the following statements are true:

'A' + 1 == 'B''A' + 2 == 'C''A' - 1 == '@''Z' - 'A' + 1 == 26 // number of letters in the alphabet
ahh thank you... that forgetting to enclose the ch = getchar() was the whole problem, it was also the reason why my program wouldnt function correctly using "ch + 1"
There's also a slightly more subtle bug in your code.

This topic is closed to new replies.

Advertisement