c - Where the first character of the string goes? -
i'm trying write exercise of "c primer plus" book. in 1 of them, faced couldn't solve or figure out what's going on. after step-by-step debugging trials, tested this:
#include <stdio.h> int main() { char str[500]; gets(str); puts(str); homecoming 0; } the output (as desired) :
exact ly every thing enter
exact ly every thing enter
but exercise i'm trying do, it's sensitive more 2 successive spaces. gets() followed puts(); don't know what's wrong. quote whole code:
/* bug: more 1 spaces next eachother. first character goes?!! write function takes string argument , removes spaces string. test in programme uses loop read lines until come in empty line. programme should apply function each input string , display result. */ #include <stdio.h> #include <string.h> int spaceremover(char *in); void takeback(char *in); int main(void) { puts("enter string space-remover: (return quit)"); { char str[500]; int spaces; gets(str); puts(str); //for debugging know finish after gets() ? //printf("\nfirst char of string: %c\n",str[0]); //printf("\nfirst char: %p '%c'\n",str,*str); spaces=spaceremover(str); printf("\n%d spaces removed: \n",spaces); puts(str); puts("\nenter string space-remover: (return quit)"); } while (getchar() != '\n'); homecoming 0; } int spaceremover(char *in) { int count=0, i; (i=0 ; i<strlen(in) ; i++) while ( *(in+i)==' ' ) //if skip more 1 space; while won't { //printf("%p '%c' \t b4: %p '%c'\n",in+i,*(in+i),in+i-1,*(in+i-1)); takeback(in+i); count++; } homecoming count; } void takeback(char *spacelocation) { int j=0; while (*(spacelocation+j)!= '\0' ) { *(spacelocation+j) = *(spacelocation+j+1); //putchar(*(spacelocation+j+1)); j++; } return; } the output:
enter string space-remover: (return quit) separated single spaces separated single spaces 5 spaces removed: thisisseparatedbysinglespaces come in string space-remover: (return quit) i'll seek more single space separators 'll seek more single space separators 13 spaces removed: 'lltrymorethansinglespaceseparators note: using blockquote one, discards successive spaces.
what's going on here? there wrong code, causing this?
(using code::blocks gcc.)
where first character of string goes?
your first character read getchar in while (getchar() != '\n');. when entered string
i'll seek more single space separators then first character i read getchar , compared \n. therefore, leaving behind
'll seek more single space separators in input buffer read gets. alter main body to:
char str[500]; puts("enter string space-remover: (return quit)"); gets(str); { int spaces; puts(str); //for debugging know finish after gets() ? //printf("\nfirst char of string: %c\n",str[0]); //printf("\nfirst char: %p '%c'\n",str,*str); spaces=spaceremover(str); printf("\n%d spaces removed: \n",spaces); puts(str); puts("\nenter string space-remover: (return quit)"); gets(str); } while (str[0]); c arrays string character
No comments:
Post a Comment