I am trying to write a function for a bigger project that consists of working with character arrays. The current function I am working on, is supposed to save only alphabetical characters and remove any special characters (Ex: ! # @ $ ? ) and spaces. My current function works, but for some reason when I run it, the first character of the array is always removed. Why is that and how can I make it to save the first character instead?
#include <stdio.h>
int main(void)
{
char phrase[101];
printf("Enter a phrase to change:");
fgets(phrase, 101, stdin);
printf("original phrase: %s", phrase);
int i = 0, j = 0;
while(phrase[i] != '\0')
{
if( ('A' <= phrase[i] && phrase[i] >= 'Z') ||
('a' <= phrase[i] && phrase[i] >= 'z') )
{
phrase[j] = phrase[i];
i++;
j++;
}
else
i++;
phrase[j] = '\0';
}
printf("new phrase: %s\n", phrase);
return 0;
}
The direction of your comparison operators is wrong. Instead of:
You need:
The way you wrote it will skip uppercase letters, which is probably why it skipped the first character of your input.
You should also move the line
phrase[j] = '\0';to after the loop, because otherwise you may overwrite the next character to be read.