I wrote a program that should take a string and then return a string with only letters from the original one, but it's not working and can't figure out why. Can someone help me?
#include<stdio.h>
char *only_letters(char *s1ptr, char *s2ptr)
{
while(*s1ptr)
{
if((*s1ptr >= 'a' && *s1ptr <= 'z') || (*s1ptr >= 'A' && *s1ptr <= 'Z'))
{
*s2ptr = *s1ptr;
s2ptr++;
}
s1ptr++;
}
*s2ptr = '\0';
return s2ptr;
}
int main()
{
char *s1ptr, *s2ptr;
printf("\n Write a string:\n");
scanf("%s", s1ptr);
printf("\n%s\n", *only_letters(s1ptr, s2ptr));
return 0;
}
You have 3 problems.
s1ptr
and s2ptr
are two unallocated arrays which will be caused to undefined behavior.
You're incrementing s2ptr
to the point which has value \0
. After returning it you will have a string that just has \0
.
To show a string, you must pass it without *
(don't dereference it).
Try this
char *only_letters(char *s1ptr, char *s2ptr_)
{
char *s2ptr = s2ptr_;
while(*s1ptr)
{
if((*s1ptr >= 'a' && *s1ptr <= 'z') || (*s1ptr >= 'A' && *s1ptr <= 'Z'))
{
*s2ptr = *s1ptr;
s2ptr++;
}
s1ptr++;
}
*s2ptr = '\0';
return s2ptr_;
}
int main()
{
char s1ptr[256]; // Long enough
char s2ptr[256]; // Long enough
printf("\n Write a string:\n");
scanf("%s", s1ptr);
printf("\n%s\n", only_letters(s1ptr, s2ptr));
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments