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 pointedstream
array pointeds
. 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:
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.be aware
toupper
works in locales single-byte character-sets.
(sameiswhite
, 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
Post a Comment