gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:21:57 25 4
gpt4 key购买 nike

我正在编写一个程序,使用 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 1the letter w was found at character 12the letter w was found at character 18the 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;
}

输出:

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

最佳答案

改变

fgets(input, 16, stdin)

fgets(input, sizeof(input), stdin)

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

来自 fgets() 联机帮助页:

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

如果您提供的多于 size -1 个字符,则剩余的字符留在输入缓冲区中

然后当程序随后调用

let = getchar();

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

关于c - 无法使用从 fgets 输入的字符串搜索字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56376827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com