Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Function to trim trailing spaces Date: Wed, 23 Jan 2019 18:46:29 -0800 Organization: None to speak of Lines: 49 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="408bb0283150d2fd02799035b8169951"; logging-data="27582"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX193O4Uf+BFW1FmhsrxySMrM" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:v4TRlKuEJO4+Zt4ptFqXjKHx8lM= sha1:RS7VGx6mZ5zjtihIufsFYQnZ35g= Xref: csiph.com comp.lang.c:140138 DFS writes: > Needed to right-trim a string (remove trailing spaces), and came up with > this: > > void rtrim(char * s) {s[strlen(s)-1]='\0';} > > > > test_rtrim.c > ------------------------------------------------ > #include > > void rtrim(char * s) {s[strlen(s)-1]='\0';} > > int main(int argc, char *argv[]) > { > char str[100]; > > printf("\nEnter some text: "); > fgets(str, sizeof(str), stdin); > fseek(stdin,0,SEEK_END); //flush stdin > > printf("Before: '%s'\n",str); > rtrim(str); > printf("After : '%s'\n",str); > } > ------------------------------------------------ > > Seems to work well. Any unobvious pitfalls? No, the pitfalls are fairly obvious. Joe Pfeiffer already pointed out that your function doesn't do what it's supposed to do and that you're missing the required `#include `. Testing the function with a string that has several trailing spaces might have saved some time. Your fseek call also doesn't do what the comment says it does. If stdin is an interactive device (which seems to be the intent), it will simply fail. There's no point in "flushing" stdin anyway, since you don't attempt to read from it again before the program finishes. And a minor point: The newline before the "Enter some text:" message is pointless. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Will write code for food. void Void(void) { Void(); } /* The recursive call of the void */