这些循环有什么区别?

问题描述 投票:0回答:1

我是C编程的初学者。 我正在通过“The C programming language second edition”(Brain W.Kerninghan 和 Dennis M.Ritchie)学习 C 在本书中,我正在练习 1-10。 “编写一个程序将其输入复制到输出,用 替换每个制表符,用 替换每个退格符,用 \ 替换每个反斜杠。这使得制表符和退格符以明确的方式可见。”

我写了一个这样的程序。


#include<stdio.h>

int main(void) {
    int c;
    
    while ((c = getchar()) != EOF) {
        if (c == '\t') {
            putchar('\\');
            putchar('t');
        }
        if (c == '\b') {
            putchar('\\');
            putchar('b');
        }
        if (c == '\\') {
            putchar('\\');
            putchar('\\');
        }
        else {
            putchar(c);
        }
    }
}

但这很奇怪。 如下所示。

C:\C>gcc Replace2.c
C:\C>a 
tab     is      like    this 
tab\t   is\t    like\t  this

在互联网上我找到了下面的程序。

#include <stdio.h>

int main()
{
    int c, d;

    while ((c = getchar()) != EOF) {
        d = 0;
        if (c == '\\') {
            putchar('\\');
            putchar('\\');
            d = 1;
        }
        if (c == '\t') {
            putchar('\\');
            putchar('t');
            d = 1;
        }
        if (c == '\b') {
            putchar('\\');
            putchar('b');
            d = 1;
        }
        if (d == 0)
            putchar(c);
    }
    return 0;
}

这很有效。

C:\C>gcc Replace2.c
C:\C>a
tab     is      like    this
tab\tis\tlike\tthis

我想知道为什么这些工作方式不同。 有人可以告诉我吗?

c stdio putchar
1个回答
0
投票

只有在不使用特殊字符时,d 变量才放置 c 字符。在您的版本中,每次不是特殊字符时都会打印 c 字符 '\'

© www.soinside.com 2019 - 2024. All rights reserved.