0

I have written this code but it only prints the word before space

void LetterCapitalize(char str[]) 
{ 

    int i;
    char res[50];
    res[0] = str[0] - 32;
    for(i=1;i<=strlen(str);i++)
    {
        if(str[i] == 32)
        {
            res[i++] = str[i++] - 32;
        }
        else
            res[i] = str[i];
    }
    printf("%s",res);
}

int main(void) { 

  // keep this function call here
  LetterCapitalize(gets(stdin));
  return 0;

}
  • 1
    1) Review `gets(stdin)`. [ref](https://linux.die.net/man/3/gets). 2) Do not use `gets()`. – chux - Reinstate Monica Jul 20 '19 at 15:41
  • 4
    Note that the [`gets()` function is too dangerous to be used — ever!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used) And you're supposed to pass `gets()` an array of characters — you're passing a file stream. Those are _not_ the same. You should use `' '` instead of 32 when you're referring to a space character. – Jonathan Leffler Jul 20 '19 at 15:43
  • Your loop `for(i=1;i<=strlen(str);i++)` will start at the _second_ char and go one _beyond_ the end [causing undefined behavior]. You want `for(i=0;i – Craig Estey Jul 20 '19 at 15:54
  • You increment i twice. And indices in C start at zero, not 1. – Paul Ogilvie Jul 20 '19 at 15:54
  • why does res[i++]=str[i++]-32 cause UB? – Atharva Chandratre Jul 20 '19 at 16:08
  • And even after fixing the UB, there is no point in continuing once you've stored `str[i] - 32`, when `str[i]` *was* 32. You just saved a terminating nullchar into `res`. Don't expect anything beyond the first space in your string, because `printf` against that `%s` will stop at that nullchar. – WhozCraig Jul 20 '19 at 16:18
  • It causes UB because your loop already loops for the entire range. It goes _beyond_ the end if it's executed. Doing `i++` _twice_ in the same statement is UB because of sequence points. Try adding (e.g.) `printf("DEBUG i=%d\n",i);` in a few places to see what happens – Craig Estey Jul 20 '19 at 16:20
  • Frankly, I'm still hung up on `gets(stdin)`. Which flavor of [`gets`](https://en.cppreference.com/w/c/io/gets) (which you shouldn't be using anyway) did you think takes a solo `FILE*` as input ? – WhozCraig Jul 20 '19 at 16:25
  • the gets(stdin) was already in the main function as i was practicing on coderbyte – Atharva Chandratre Jul 20 '19 at 17:33

0 Answers0