【问题标题】:Why doesn't backspace undo a lone getchar() call in C?为什么退格键不撤消 C 中单独的 getchar() 调用?
【发布时间】:2015-11-08 02:09:59
【问题描述】:

示例代码是(cmets 是我想象它在第一个循环中所做的):

#include <stdio.h>

#define BACKSPACE 8

main()
{
    int c;


    while((c = getchar()) != EOF)     //output: GODDAMN NOTHING    cursor on: 'h'
    {
        //if the input is "house" before entering EOF
        putchar(c);                  //output: 'h'   cursor on: 'o'

        getchar();                   //output: 'h'   cursor on: 'u'
        printf("%c", BACKSPACE);     //output: 'h'   cursor on: 'o'
        getchar();                   //output: 'h'   cursor on: 'u'
        printf("%c", BACKSPACE);     //output: 'h'   cursor on: 'o'
        getchar();                   //output: 'h'   cursor on: 'u'
        printf("%c", BACKSPACE);     //output: 'h'   cursor on: 'o'
    }
}       //ACTUAL END OUTPUT: "h"

我知道大多数程序中的常规退格如下所示: printf("%c %c", 8 ,8); ..意思是退格几乎只是将光标向后移动而不删除任何内容,就像 getchar() 只是向前移动光标一样。

我试图理解为什么上面的示例代码的输出与以下内容不完全相同:

#include <stdio.h>

main()
{
    int c;


    while((c = getchar()) != EOF)     //output: WE HAVE NOTHING    cursor on: 'h'
    {
        //if the input is "house" before entering EOF
        putchar(c);          //output: 'h'   cursor on: 'o'
    }
}       //ACTUAL END OUTPUT: "house"

编辑:跟进问题!如何“反转” getchar() 调用?

#include <stdio.h>

main()
{
    int c;
    char a;


    while((c = getchar()) != EOF)
    {
        a = c;
        putchar(c); 

        a = getchar();
        ??????????
    }
}

我必须在“?????????之后。

【问题讨论】:

    标签: c getchar backspace


    【解决方案1】:

    您的程序实际上并不是一次从终端读取一个字符。相反,它从一个缓冲区中读取,该缓冲区包含您输入的整行。

    所以:

    • 阅读h后,你的程序
      • 打印h,
      • 从缓冲区读取o,然后
      • 发送一个退格键(将光标放在h
    • 然后它读取u,并且
      • 发送一个退格键(试图将光标移到左边距之前),
    • 然后它读取s,并且
      • 发送另一个退格键
    • 完成循环并输入更多字符

    有些终端会将光标回绕到上一行的末尾,有些终端会停在边缘。

    【讨论】:

      【解决方案2】:

      您的输出实际上与您输入的来源不同。

      终端收集您的击键。当您键入时,它会显示并记住它们。当您按 ENTER 时,它会将它记住的击键发送到您的程序。

      同时,它显示程序的输出。您也许可以让终端擦除您输入的字符的显示,但这不会改变它对您输入的字符的记忆,也不会改变发送到您的程序的字符。

      要撤消一个单个 getchar(),你可以使用ungetc:

      http://www.cplusplus.com/reference/cstdio/ungetc/

      【讨论】:

        猜你喜欢
        • 2017-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        • 2014-01-13
        • 2012-03-17
        • 1970-01-01
        • 2015-08-31
        相关资源
        最近更新 更多