Я пишу программу для поиска местоположения определенного символа в строке, используя strchr
. При использовании fgets
для ввода строки от пользователя программа не выполняется должным образом.
Однако при использовании gets
все работает нормально.
Код, который работает с использованием 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;
}
Выход:
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
Код, который не работает 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;
}
Выход:
what is the string that you would like to check?
what is the character that you would like to find?
in string "abcdefghijklmno"...