【问题标题】:Write a program to copy input to output编写程序将输入复制到输出
【发布时间】:2019-06-24 00:41:45
【问题描述】:

我正在尝试编写一个将其输入复制到其输出的程序。我假设如果给定以下字符串:“Hello I am /c”,它应该输出:“Hello \t am \c”我是否正确?

我尝试在线阅读有关 stdio.h 库的信息。

#include <stdio.h>
/* Write a program to copy its input to its output, replacing each tab by \t, each backspace by \b, and each backslash by \\. This makes tabs and backspaces visible in an unambigous way.*/

int main()
{
    char c;

    while ((c = getchar()) != EOF){

        if ((c = getchar()) == '\t'){
            putchar('\t');
        }
        if (c == '\b'){
            puts("\b");
        }
        if (c == '\\'){
            puts("\\");
        }

        putchar(c);
    }

}

请帮助我进一步理解这个问题并解释为什么我的代码不起作用。

【问题讨论】:

  • 假设您解决了 David 已经发现的问题 - 使用原样的代码,您将 复制 有问题的三个字符,但不会替换它们。还是你想生成 C 风格的转义字符串?
  • 可以简单到int c; while ((c = getchar()) != EOF) putchar (c);

标签: c char


【解决方案1】:

两个问题。第一:

while ((c = getchar()) != EOF){

您应该将getchar() 的返回值与EOF 进行比较。在这里,您将cEOF 进行比较。这是不正确的,因为cchargetchar 返回int。因此,您应该将intEOF 进行比较,并将charEOF 进行比较。错了。

第二:

    if ((c = getchar()) == '\t'){

你为什么又打电话给getchar?您不想阅读其他字符。

【讨论】:

  • 我明白了。我也在使用 while ((c = getcjar())!=EOF,因为它返回用户输入到输出流中的字符串或字符。我的意思是运行,它在某种程度上满足了我的要求。
【解决方案2】:
#include <stdio.h>
/* Write a program to copy its input to its output, replacing each tab by \t, each backspace by \b, and each backslash by \\. This makes tabs and backspaces visible in an unambigous way.*/
// c is a char and getchar returns an int
int main()
{
    char c;

    while ((c = getchar()) != EOF)
    {

        if (c == '\t'){
            //putchar('\t');
            printf("\\t");
        }
        else if (c == '\b'){
            printf("//b");
            //puts("\b");
        }
        else if (c == '\\'){
            printf("\\\\");
            // no, this is gay(Ruby code) -> puts("\\");
        } else  {

        putchar(c);
        }
    }

}

我的代码很相似——我只是忘记了我也可以只在 C 中使用 ``printf()` 而不是使用更严格的函数 putchar()。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2023-03-11
    • 1970-01-01
    • 2011-05-25
    • 2017-02-06
    相关资源
    最近更新 更多