gpt4 book ai didi

c - 字符串检查 c pangramm 中带有制表符的字母

转载 作者:行者123 更新时间:2023-11-30 16:34:56 26 4
gpt4 key购买 nike

我已经编写了这段代码,但我遇到了一些问题。这段代码应该获取一个字符串并检查该字符串是否包含所有字母......如果没有,输出是“Not a pangramma!”。如果它确实“PanGramma!”。问题是我希望它也计算单词之间的空格数。但是,当输入是至少有一个空格的字符串时,输出将始终是“Not a PanGramma!”,即使它包含所有字母。有人可以帮我吗?

    #include <stdio.h>
char UpCase (char c);
int isPangram (char *str);

int main()
{
char str[100];
printf("Please enter yout string: \n");
scanf("%s", str);
if (isPangram (str) == 1)
{
printf("PanGramma!\n");
}
else
{
printf("Not a PanGramma!\n");
}

return 0;
}
char UpCase (char c)
{
if (c>='a' && c<='z')
{
return c-'a'+'A';
}
return c;
}
int isPangram (char *str)
{
int i=0;
int hist[27]={0};
while (str[i] !=0)
{
str[i]=UpCase(str[i]);
if (str[i] == ' ')
{
hist[26]++;
}
else
{
hist[str[i] - 'A']++;
}
i++;
}
for (i=0; i<26; i++)
{
if(hist[i] == 0)
{
return 0;
}
}
return 1;
}

最佳答案

您的问题来自于 scanf 函数的使用:它确实在捕获的每个空白处停止。

来自man scanf :

%s

Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

要使您的程序正常运行,您可以使用 fgets功能:

int main()
{
char str[100];
printf("Please enter yout string: \n");

fgets(str, sizeof str, stdin);

if (isPangram (str) == 1)
{
printf("PanGramma!\n");
}
else
{
printf("Not a PanGramma!\n");
}

return 0;
}
<小时/>

如果您想了解更多关于scanf函数的信息,您可以阅读A beginners' guide away from scanf() 。它还会告诉您为什么 scanf 可能会导致代码中的缓冲区溢出。

关于c - 字符串检查 c pangramm 中带有制表符的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49131611/

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