gpt4 book ai didi

c - 查找不在一系列单词中的缺失小写字母

转载 作者:行者123 更新时间:2023-11-30 16:35:41 24 4
gpt4 key购买 nike

正如标题中所述,我试图找到一系列单词中的所有小写字母。没有大写字母、数字、标点符号或特殊符号。

我需要帮助修复我的代码。我被困住了,不知道该去哪里。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void){
int letters[26];
char words[50];
int i = 0, b = 0;

printf("Enter your input : ");
scanf("%s", words);

for(i = 0; i < 26; i++){
letters[i] = 0;
}

while(!feof(stdin)){

for(b = 0; b < strlen(words) - 1; b++){
letters[ words[b] - 'a']++;
scanf("%s", words);
}
}

printf("\nMissing letters : %c ", b + 97);


return 0;
}

我的输出给了我一些随机字母,我不知道它来自哪里。

最佳答案

这是一个可行的第一个实现。

除了已经做出的注释之外,您还应该尽可能使用函数将程序的功能分离为逻辑步骤。然后,您的主函数应该调用适当的函数来解决问题。每个函数都应该是独立且可测试的。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX_INPUT 20 /* Max input to read from user. */

char *readinput(void);
void find_missing_lower_case(char *, int);

int main()
{
char *user_input = readinput();
int len_input = strlen(user_input);

printf("user input: %s\n", user_input);
printf("len input: %d\n", len_input);

find_missing_lower_case(user_input, len_input);

/* Free the memory allocated for 'user_input'. */
free(user_input);
return 0;
}

char *readinput()
{
char a;
char *result = (char *) malloc(MAX_INPUT);

int i;
for(i = 0; i < MAX_INPUT; ++i)
{
scanf("%c", &a);
if( a == '\n')
{
break;
}
*(result + i) = a;
}

*(result + i) = '\0';
return result;
}

void find_missing_lower_case(char *input, int len_input)
{
int a = 97; /* ASCII value of 'a' */
int z = 122; /* ASCII value of 'z' */

int lower_case_chars[26] = {0}; /* Initialise all to value of 0 */

/* Scan through input and if a lower case char is found, set the
* corresponding index of lower_case_chars to 1
*/
for(int i = 0; i < len_input; i++)
{
char c = *(input + i);
if(c >= a && c <= z)
{
lower_case_chars[c - a] = 1;
}
}

/* Iterate through lower_case_chars and print any values that were not set
* to 1 in the above for loop.
*/
printf("Missing lower case characters:\n");
for(int i = 0; i < 26; i++)
{
if(!lower_case_chars[i])
{
printf("%c ", i + a);
}
}
printf("\n");
}

关于c - 查找不在一系列单词中的缺失小写字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48797251/

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