无法使用fgets输入的字符串搜索字符

时间:2019-05-30 10:51:31

标签: c char fgets gets

我正在编写一个程序,使用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

使用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"...

2 个答案:

答案 0 :(得分:2)

更改

fgets(input, 16, stdin)

fgets(input, sizeof(input), stdin)

当您将16的参数传递给fgets()时,指示它读取的字符数不能超过15个。为什么?

fgets()联机帮助页中:

  

fgets()从流中读取最多小于字符,并将它们存储到s指向的缓冲区中。

如果您提供的个字符超过size -1 个,则其余字符将留在输入缓冲区中

然后程序随后调用时

let = getchar();

let被分配了输入缓冲区中的下一个字符,而无需等待您键入其他任何内容。然后,它将在您提供的字符串中搜索该字符-但在您提供的示例中找不到该字符。

答案 1 :(得分:0)

在第一个代码段中调用

gets (input);

不限制用户可以输入的字符数。请注意,函数gets不受C标准支持并且不安全。

在第二个代码段中,您将变量input声明为

char input[50];

因此,通过以下方式调用fgets更自然

fgets (input,sizeof( input ),stdin );

代替

fgets (input,16,stdin);

标准功能getchar读取任何字符,包括空格。

因此,最好使用

scanf( " %c", &let );

否则,getchar可以读取输入缓冲区中留下的任何字符(包括换行符)。 scanf的调用会跳过任何空格字符。