--小心前面可怕的新手代码--
我正试图将这个简单的计数程序从while重写为for

int c, nc;

nc = 0;
while ((c = getchar()) != EOF) {
    if (c != '\n')
        ++nc;
    }
}
printf("%d\n", nc);

这将输出example->8
到目前为止,我尝试了以下两个例子:
int c, nc;
for (nc = 0; ((c = getchar()) != EOF && (c = getchar()) != '\n'); ++nc)
    ;
printf("%d", nc);


int nc;
for (nc = 0; getchar() != EOF; ++nc)
    if (getchar() == '\n')
        --nc;
printf("%d", nc);

这两种尝试都会导致奇怪的输出,如example->3a->0,而且程序在接收到输入后不再“等待”中断,它只是显示输出并关闭自己。
我想知道这里发生了什么,因为在我看来,我只是插入(相当笨拙…)一张支票,似乎无法解释发生了什么。。

最佳答案

你打了两次电话

for (nc = 0; getchar() != EOF; ++nc)
    if (getchar() == '\n')
        --nc;
printf("%d", nc);

试试这个吧
int chr;
int nc;

chr = fgetc(stdin);
for (nc = 0 ; chr != EOF ; nc += (chr == '\n') ? 0 : 1)
    chr = fgetc(stdin);
printf("%d\n", nc);

getchar()相当于从输入流中读取一个字符,一旦读取了该字符,就必须对其进行处理,因为它已从流中移除,因此调用函数两次将从getchar()中移除两个字符,因此您的计数将是错误的。
因此,如何编写for循环并不重要,重要的是每次迭代调用一次fgetc(stdin),例如这可以工作
int chr;
int nc;

for (nc = 0 ; ((chr = fgetc(stdin)) != EOF) ; nc += (chr == '\n') ? 0 : 1);
printf("%d\n", nc);

或者这个
int chr;
int nc;

for (nc = 0 ; ((chr = fgetc(stdin)) != EOF) ; )
{
    if (chr != '\n')
        nc += 1;
}
printf("%d\n", nc);

注意stdin被称为ternary operator,相当于
if (condition)
    x = value;
else
    x = another_value;

关于c - C-使用if语句在for循环中重写while循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28191655/

10-11 23:13
查看更多