有人可以为我解释for循环吗?

时间:2014-09-01 03:03:20

标签: c string reverse

#include <stdio.h>
#define MAXLINE 10

void reverse(char s[]);
void getline(char b[], int lim);

int main() {
char s[MAXLINE];
getline(s, MAXLINE);
reverse(s);
return 0;
}

void reverse(char s[]) {
    int i;
    int len = 0;
    for (i=0; s[i] != '\0'; i++) {
        len = len + 1;
    }
    char b[len + 1];
    for (i = 0; i < len; i++) {
        b[(len - 1) - i] = s[i];
    b[len] = '\0';
    }
    printf("%s : %s\n", s, b);
}

void getline(char b[], int lim) {
    char c;
    int i;
    for (i=0; i < lim-1 && (c = getchar())!= EOF && (c!='\n'); ++i) {
        b[i] = c;
    }
    if (c == '\n') {
        b[i] = '\n';
    }
}

为什么我的get line unction出现错误?它在Xcode中表示&#34;&#39; get line&#39;的冲突类型。另外在另一个错误中,它表示&#34;函数调用的参数太少,预期为3,有2个?

也可以有人解释&#34;条件&#34;的评估顺序。 for循环的一部分? (我正在谈论&amp;&amp;&amp;&#;;)。非常感谢!!!

1 个答案:

答案 0 :(得分:0)

(1)..你的程序是正确的。但是,库中已经存在一个库函数getline。我们知道预定义函数的原型声明存在于头文件中。对于getline预定义函数,声明已经存在于stdio.h ...在你的程序中,你也被宣告为getline的原型。我们知道一个函数不可能有两个声明。所以只有你有错误。尝试使用该函数的其他名称运行程序...

(2).. for (i=0; i < lim-1 && (c = getchar())!= EOF && (c!='\n'); ++i)

在for循环中你正在检查三个条件..你正在检查'\ n'也是。所以,你应该只输入字符串格式。但实际上它不是字符串。你应该连续输入字符作为输入而不按ENTER键。

相关问题