所以,我只是在学习如何在C中进行编码,而我对老师的要求感到有些困惑。基本上,我们需要创建一个程序,该程序通过字符读取两个单独的文件字符的字符,如果两个字符完全相同,则将其打印到第三个文件。通常,我会使用一个数组来执行此操作,但是,我们被特别被告知我们不允许使用数组。我有点让它正常打印到第三个文件的字符,但是除了字符外,它还打印数字和标点符号。显然,我缺少一些东西,但我不知道那是什么。这是我的代码:
int main(int argc, char *argv[]) {
FILE *fp, *fp2, *ofp;
char a, b;
fp = fopen("input1a.txt", "r");
fp2 = fopen("input1b.txt", "r");
ofp = fopen("output.txt", "w");
while((a=getc(fp))!= -1){
b=getc(fp2);
if(isalpha(a) == isalpha(b)){
putc(a, ofp);
letters++;
}
}
return 0;
}
根据我阅读的内容,Isalpha应该检查一下字符是否是字母字符,但是在这种情况下,我有更好的使用吗?感谢您提供的任何帮助!
这是问题
if(isalpha(a) == isalpha(b)) {
应该是
if (isalpha(a) && isalpha(b) && a == b)
您不是在比较字符是否相等,而是在比较两者是否均为字母,如果它们都是字母,或者都是字母,或者都是不是字母的字母文件。
此外,还习惯于编写安全的代码,该代码也很干净且可读,如以下内容(请注意,有一些优雅的方法来处理错误,您可以添加错误消息):
int main(int argc, char *argv[])
{
FILE *in[2];
FILE *out;
int chars[2]; // getc() returns `int' not `char'
int counter;
in[0] = fopen("input1a.txt", "r");
if (in[0] == NULL)
return -1;
in[1] = fopen("input1b.txt", "r");
if (in[1] == NULL) {
fclose(in[0]);
return -1;
}
output = fopen("output.txt", "w");
if (output == NULL) {
fclose(in[0]);
fclose(in[1]);
return -1;
}
counter = 0;
while (((chars[0] = getc(in[0])) != EOF) && ((chars[1] = getc(in[1])) != EOF) {
if (chars[0] == chars[1] && isalpha(chars[0])) {
putc(chars[0], out);
counter++;
}
}
// Release ALL resources, it's a good habit
fclose(inputs[0]);
fclose(inputs[1]);
fclose(output);
// Not required but a good habit too
return 0;
}
不要使用魔术数字, EOF
通常是-1,但最好使用 EOF
使代码可读且健壮。