For循环忽略测试表达式

时间:2014-08-27 21:41:56

标签: c loops for-loop

我是新手程序员,我的程序中的for循环有问题,循环创建字母' A'到了' Z'在一封char"字母"但是我的循环并没有停留在字母“Z'它只是无限期地继续前进,有人可以帮助我吗?

提前致谢

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

FILE * fptr;

int main()
{
    char letter;
    int i;

    fptr = fopen("C:\\Users\\Wim\\Documents\\C\\random read write to                      
       file\\letters.txt", "w+");

    if (fptr == 0)
    {
        printf("There was a error while opening the file! ");
        exit(1);
    }

    for (letter = 'A'; letter <= 'Z'; letter++)//This is the offending part of the code!
    {
        fputc(letter, fptr);
    }

    puts ("You just wrote the letters A through Z");

    fseek(fptr, -1, SEEK_END);
    printf("Here is the file backwards :\n");

    for (i= 26; i > 0;i++)
    {
        letter = fgetc(fptr);
        fseek(fptr, -2, SEEK_CUR);
        printf("The next letter is %c .\n", letter);
    }

    fclose(fptr);

    return 0;

}

1 个答案:

答案 0 :(得分:3)

此循环

for (i= 26; i > 0;i++)

错了。必须有

for ( i= 26; i > 0; i-- )

我也会按照以下方式编写这个循环

for ( i = 'Z' - 'A' + 1; i > 0; i-- )