c - Function returns only letters of string -
i wrote program should take string , return string letters original one, it's not working , can't figure out why. can 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 string:\n"); scanf("%s", s1ptr); printf("\n%s\n", *only_letters(s1ptr, s2ptr)); return 0; }
you have 3 problems.
s1ptr
,s2ptr
2 unallocated arrays caused undefined behavior.you're incrementing
s2ptr
point has value\0
. after returning have string has\0
.to show string, must pass 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 string:\n"); scanf("%s", s1ptr); printf("\n%s\n", only_letters(s1ptr, s2ptr)); }
Comments
Post a Comment