Sign in to follow this  
EvilCloneVlad

C program to replace char's

Recommended Posts

EvilCloneVlad    114
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.

Share this post


Link to post
Share on other sites
fastcall22    10846

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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this