Search code examples
ccharfgetsgets

Unable to search character with string input from fgets


I'm writing a program to find the location of a certain character in a string using strchr. When using fgets to input the string from the user, the program does not execute properly.

However when using gets everything works fine.

Code that works using gets():

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

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    gets(input);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the letter %c was found at character %d\n", let, ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}

Output:

what is the string that you would like to check?
what is the character that you would like to find?
in string "why is the world when wondering"...
the letter w was found at character 1
the letter w was found at character 12
the letter w was found at character 18
the letter w was found at character 23

Code that does not work usgin fgets():

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

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    fgets(input, 16, stdin);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the character is found at %d \n", ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}

Output:

what is the string that you would like to check?
what is the character that you would like to find?
in string "abcdefghijklmno"...

Solution

  • Change

    fgets(input, 16, stdin)
    

    to

    fgets(input, sizeof(input), stdin)
    

    When you pass an argument of 16 to fgets() you are instructing it to read no more than 15 characters. Why?

    From the fgets() manpage:

    fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.

    If you provide more than size -1 characters, the remaining characters are left in the input buffer.

    Then when the program subsequently calls

    let = getchar();
    

    let is assigned whatever the next character in the input buffer is - without even waiting for you to type anything else. It then searches for this character in the string you provided - but in the example you provided doesn't find it.