Jump to content
  • Advertisement
Sign in to follow this  
EvilCloneVlad

C program to replace char's

This topic is 2807 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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

Share this post


Link to post
Share on other sites
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"

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!