0

I'm trying to find bug in the following program.

If I give input as "This is a test", output shows "This Is A". I'm trying to find out why "Test" is missing.

Please help me to understand the problem. Thanks in advance.

#include<stdio.h>
#include<string.h>

int main()
{
    char str[1000], word[100];
    int i, j, length, is_word_started;

    gets(str);
    length=strlen(str);
    is_word_started=0;

    for(i=0, j=0; i<length; i++)
    {
        if(str[i]>='a' && str[i]<='z')
        {
            if(is_word_started==0)
            {
                is_word_started=1;
                word[j]='A'+str[i]-'a';
                j++;
            }
            else
            {
                word[j]=str[i];
                j++;
            }
        }
        else if(str[i]>='A' && str[i]<='Z' || str[i]>='0' && str[i]<='9')
        {
            if(is_word_started==0)
            {
                is_word_started=1;

            }
            word[j]=str[i];
            j++;
        }
        else
        {
            if(is_word_started==1)
            {
                is_word_started=0;
                word[j]='\0';
                printf("%s\n", word);
                j=0;
            }
        }
    }

    return 0;
}
Reaz
  • 7
  • 1
  • 5
  • 2
    @usr You should explain [Why is the gets function so dangerous that it should not be used?](http://stackoverflow.com/q/1694036/613130) – xanatos Mar 08 '17 at 14:15
  • @usr Sadly "scholastic" C often doesn't include the chapter "how to write safe and secure C code" :-) – xanatos Mar 08 '17 at 14:22
  • when compiling, always enable all the warnings, then fix those warnings (don't hide them) (for `gcc`, at a minimum use: `-Wall -Wextra -pedantic` I also use: `-Wconversion -std=gnu11` ) – user3629249 Mar 09 '17 at 23:33

1 Answers1

2

You must repeat the

if(is_word_started==1)
{
    is_word_started=0;
    word[j]='\0';
    printf("%s\n", word);
    j=0;
}

outside the for () cycle (at the end of its })

Otherwise when you finish parsing the str, the letters you were accumulating in word are "lost".

Technically you could short it to:

if(is_word_started==1)
{
    word[j]='\0';
    printf("%s\n", word);
}

because after that you won't reuse those variables.

Other than the "Never use gets()" suggested by @usr, you should correctly-size word: always use the worst case. If str[1000] then word[1000]!

xanatos
  • 109,618
  • 12
  • 197
  • 280