8.2 习题编写一个程序,在遇到EOF之前,把输入作为字符流读取,程序需要打印每个输入的字符及其相应的ASCLL十进制..........

#include <stdio.h>
int main(void)
{
    char ch;
    int number = 0;

    printf("please enter the word you want to print: ");
    while((ch = getchar() != EOF)) //错误点!
    {
        switch (ch)
        {
        case '\n':
            printf("\\n");
            printf("%d  ",ch);
            break;
        case '\t':
            printf("\\t");
            printf("%d  ",ch);
             break;
        default:
            if(ch < ' ')
               {
                putchar('^');
                putchar(ch+64);
                printf(":%d ", ch);
               }
            else
               {
                putchar(ch);
                printf(":%d ", ch);
                 break;
               }
            }
       number++;
       if(number %10 == 0)
           putchar('\n');
    }
    return 0;
}



一直没有找到错误,发现程序只会进入default 中的第一个if ,并且ch的值一直是1,最后发现 是在while 循环里面的括号错了,(应该是 (ch = getchar()) != EOF), 按照我这样写的话, 由于运算优先的顺序,会先执行 getchar()!= EOF, 那么这样执行的结果 要么为1 要么为0 ,这样ch的值就在这两个值中。从而导致了错误。!!!!!!!下次一定要注意!,,,,并且switch 不能用在于浮点型中。

猜你喜欢

转载自blog.csdn.net/qq_36324796/article/details/78920390