【发布时间】:2015-01-13 07:18:30
【问题描述】:
感谢您查看我的问题!
我正在尝试从 C 中的教科书示例练习创建一个工作程序(我仍然是初学者,我正在通过书籍/笔记学习),它将确定用户输入的两个字符串是否是字谜(无论大小写或间距)。 为什么我的程序正在编译,但没有通过第一个 getString 提示以允许用户输入第二个字符串? 以下是练习的目标,以及到目前为止我编写的代码(在底部)。
算法 读取第一个字符串,然后编写一个循环,该循环使用 26 个整数的数组来计算有多少个整数 每个字母被看到的次数。 读取第二个字符串,这一次减少 int 数组中每个字母的计数。 如果 int 数组中的每个元素都是 0,则字符串是字谜。 忽略任何不是字母的字符。将大写字母视为与它们相同 小写等效。下面给出了这方面的帮助。
所需功能 您需要使用以下功能。您必须设计适当的参数 和返回类型。如果它们使您的程序更简单,您还可以添加其他功能 更清晰。
main() 声明变量,然后调用下面描述的函数来解决问题。
初始化() 在读取第一个字符串之前清除所有 char 和 int 数组的内容。 (将 char 数组中的每个元素设置为空字符“\0”。)
getString() 提示并从输入中读取字符串。 执行此操作时,从中调用标准库函数 gets()。功能 原型是:char *gets(char s[]);将下一个输入行读入字符串 s;它将终止的换行符替换为“\0”。 如果文件结束或发生错误,则返回 s 或 NULL。
setLetters() 循环遍历第一个字符串中的每个字符, 并更新 int 数组中该字母的计数。 调用以下标准库函数 当你这样做时。函数原型是:
int isalpha(char c) 如果字符 c 是小写或大写字母,则返回非零 (true)
char tolow(char c) 如果字符 c 为大写字母,返回对应的小写字母;否则返回 c
checkLetters() 循环遍历第二个字符串中的每个字符,并从 int 数组中该字母的计数中减去 1。与 setLetters() 非常相似。
isZero() 循环 int 数组。如果每个元素都为 0,则返回 TRUE,否则返回 FALSE。
这是我到目前为止编写的代码,它可以编译但没有到达第二个字符串:
#include <stdio.h>
#include <ctype.h>
#define ABC 26
/* lab5.c: Compares user input to determine if they are anagrams */
char initialize(char s1[], char s2[], int count[]);
char getString(char s[]);
char *gets(char s[]);
int setLetters(char s1[], int count[]);
int checkLetters(char s2[], int count[]);
int isZero(int count[]);
int main() {
char string1[100];
char string2[100];
int count1[ABC] = {0};
initialize(string1, string2, count1);
getString(string1);
setLetters(string1, count1);
getString(string2);
checkLetters(string2, count1);
isZero(count1);
}
char initialize(char s1[], char s2[], int count[]) {
int i;
for (i = 0; s1[i] != '\0'; i++) {
s1[i] = '\0';
s2[i] = '\0';
count[i] = 0;
}
}
int setLetters(char s1[], int *count[]) {
int i = 0;
while (s1[i] != '\0') {
if (isalpha(s1[i])) {
count[tolower(s1[i]) - 'a']++;
i++;
}
}
return count;
}
int checkLetters(char s2[], int count[]) {
int i;
while (s2[i] != '\0') {
if (isalpha(s2[i])) {
count[tolower(s2[i]) - 'a']--;
i++;
}
}
}
char getString(char s[]) {
printf("Enter the string: ");
gets(s);
}
int isZero(int count[]) {
int i;
int x = 0;
for (i = 0; i < ABC; i++) {
if (count[i] != 0)
x = 1;
}
if (x == 1) {
printf("Not Anagram");
}
else {
printf("Anagram");
}
}
输出:
Enter the string: mattress
Enter the string: smartest
Not Anagram
...这不是完全正确的输出。 :P
【问题讨论】:
-
今天早些时候不是有人问过这个问题吗?
-
您的代码有几个问题;它甚至不应该首先编译。
setLetters被声明为返回int,但它返回一个指向int的指针。initialize声明返回char(为什么???),但它不返回任何内容。getString的原型与作业中列出的不同。 -
从不,从不,从不使用
gets由于严重的安全问题,它不再是 C 标准的一部分。请改用fgets、getline或scanf。 (getline提供了一些其他人不喜欢的细节,返回实际读取的字符数,如果lineptr设置为NULL,则分配内存来保存您的输入)但是一切都会正常工作。 (这个问题已经在几个小时前回答了) -
@paulalucai 标记您的问题已解决,press the check-mark near the answer that helped you。
-
我已经通过解决方案回滚了您对问题的替换。请找到your solution in the revision history 并将其作为自己的答案发布。