I can't seem to understand what is creating the next line in this C program -


(homework question) program meant capitalize first letter of each string, need put period behind input. can't seem function capital generates \n reason not aware of. appreciated! need bit, got else.

#include <stdio.h> #include <string.h> #include <ctype.h> int capital(char s[]) {     int i;     for(i=0; i<strlen(s); i++)     {         if (i==0||(s[i-1]==' '&&s[i]>='a'&&s[i]<='z'))         s[i]=toupper(s[i]);     }     printf("%s.", s);  return 0; }  int main() {     char s[100];     printf("please enter line of text > ");     fgets(s, sizeof(s), stdin);     capital(s);     return 0; } 

so example want output like

please enter line of text > me stackoverflow me stackoverflow. 

as opposed right now

please enter line of text > me stackoverflow me stackoverflow . 

fgets preserves newline.

7.21.7.2 fgets function

#include <stdio.h> char *fgets(char * restrict s, int n, file * restrict stream); 

2 fgets function reads @ 1 less number of characters specified n stream pointed stream array pointed s. no additional characters read after new-line character (which retained) or after end-of-file. null character written after last character read array.


some other things:

  1. it's bad idea use strlen in termination condition.
    makes algorithm quadratic, unless compiler succeeds in determining string not shortened in loop, , don't want depend on it.

    test s[i] instead.

  2. be aware toupper works in locales single-byte character-sets.
    (same iswhite, wanted use checking whitespace.)

    anyway, checking 'a'-'z' before calling it, why don't finish it?

    if ( (!i || s[i-1]== ' ') && s[i]>='a' && s[i]<='z')     s[i]+='a'-'a'; 

    (btw: condition curious.)


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -