简体   繁体   中英

Program to copy its input to its output, replacing each tab by \t , each backspace by \b , and each backslash by \\

I am trying to solve this K&R question. I tried this code in CodeBlocks.

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

But when i press backspace \\b is not being displayed in place of that. 在此处输入图片说明

Please help me.

It's because the console window handles keyboard and editing keys itself.

You have to look into the Windows console functions , especially the SetConsoleMode function.


To clear the ENABLE_PROCESSED_INPUT and ENABLE_LINE_INPUT flags:

// Get the console handle for `stdin`
HANDLE hConsoleStdin = GetStdHandle(STD_INPUT_HANDLE);

// Get the current flags
DWORD flags;
if (GetConsoleFlags(hConsoleStdin, &flags))
{
    // Now `flags` contain the current flags
    // Remove the flags we don't want there
    flags &= ~(ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT);

    // And finally set the new flags
    SetConsoleFlags(hConsoleStdin, flags);
}

Note: The above code is not tested, as I don't have access to a Windows machine.

The problem actually is, your console does not pass the back-space to the program, but deletes the character from the input-buffer. As @JoachimPileborg said, see the use of SetConsoleMode and other functions.

这里回答了如何在Linux环境中完成此操作的详细信息。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM