Search code examples
cscanfstdiofgets

Tips on how to read last 'word' in a character array in C


Just looking to be pointed in the right direction:

Have standard input to a C program, I've taken each line in at a time and storing in a char[].

Now that I have the char[], how do I take the last word (just assuming separated by a space) and then convert to lowercase?

I've tried this but it just hangs the program:

while (sscanf(line, "%s", word) == 1)
    printf("%s\n", word);

Taken what was suggested and came up with this, is there a more efficient way of doing this?

char* last = strrchr(line, ' ')+1;

while (*last != '\0'){   
    *last = tolower(*last);
    putchar((int)*last);
    last++;
}

Solution

  • If I had to do this, I'd probably start with strrchr. That should get you the beginning of the last word. From there it's a simple matter of walking through characters and converting to lower case. Oh, there is the minor detail that you'd have to delete any trailing space characters first.