编写程序以将输入复制到输出 [英] Write a program to copy input to output

查看:55
本文介绍了编写程序以将输入复制到输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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.

推荐答案

两个问题.首先:

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

您应该将 getchar()的返回值与 EOF 进行比较.在这里,您将 c EOF 进行比较.这是不正确的,因为 c char ,而 getchar 返回 int .因此,您应该将 int EOF 进行比较,并且将 char 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.

第二:

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

您为什么再次致电 getchar ?您不想读取其他字符.

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

这篇关于编写程序以将输入复制到输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆