Write a program to copy input to output

前提是你 提交于 2021-01-29 10:59:53

问题


I am trying to write a program that copies its input to its output. I am assuming that if I am given the following string: "Hello I am /c" it should output: "Hello \t am \c" am I correct?

I have tried reading online about the stdio.h library.

#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);
    }

}

Please help me further understand this question and explain why my code does not work.


回答1:


Two problems. First:

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

You're supposed to compare the return value of getchar() to EOF. Here, you compare c to EOF. That's incorrect because c is a char and getchar returns an int. So you're supposed to be comparing an int to EOF and you are comparing a char to EOF. That's wrong.

Second:

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

Why are you calling getchar again? You don't want to read another character.




回答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);
        }
    }

}

my code was similar - I just forgot that I could also just ``printf()` in C instead of using the much more strict function putchar().



来源:https://stackoverflow.com/questions/56728692/write-a-program-to-copy-input-to-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!