【发布时间】:2021-08-25 13:25:58
【问题描述】:
我正在做作业,快完成了。这是我的代码
#include <stdio.h>
#include <stdlib.h>
void main()
{
char word[100],*ptr,input;
int count,i,n;
printf("Enter the word : ");
scanf("%[^\n]", word);
ptr = &word;
do
{
printf("Enter the letter : ");
scanf(" %c", &input);
if(input == '-'){
printf("Exit.");
return 0;
}
for(i=0;word[i] != '\0';i++)
{
if(*ptr == input)
count++;
ptr++;
}
printf("Has %d of '%c'",count,input);
printf("\n");
}while(input != '-')
}
此代码将提取字符串中的字母数
例如:如果您输入“WWWWooo”,它将给出“有 4 个 'W'”和“有 3 个 'o'”
当您输入“-”字母时,代码将退出。
我发现的问题是“计数”值似乎仍然是我要查找的第一个字母的总数。
我的期望:“WWWWooo”将给出“有 4 个‘W’”和“有 3 个‘o’”
我得到的是“有 4 个 'W'”和“有 4 个 'o'”。计数值未重置。
我尝试将 count = 0; 放在 do while 循环的顶部,扫描的第二个字母的输出将始终为 0。
我该如何解决这个问题?
【问题讨论】:
-
把 count = 0 放在最后,在 printf 之后
-
不仅
count需要重置,ptr也需要重置。但无论如何你都可以摆脱ptr。将*ptr == input替换为word[i] == input。这更有意义,因为您在for条件和正文中使用相同的变量 -
请仔细检查您是否显示了minimal reproducible example。显示的代码 a) 无法编译 b) 有明显的修复,不符合描述的行为。
-
@Fabiobreo 我试过了,每次都返回 0
-
您需要同时进行评论提案,Fabios 和 Ingos。 (并修复一些其他问题......)然后我得到
Enter the word : Enter the letter : Has 4 of 'W' Enter the letter : Has 3 of 'w' Enter the letter : Exit.例如这里tutorialspoint.com/compile_c_online.php请学习阅读和修复编译器警告,不仅仅是错误。