【问题标题】:Remove new line character from console从控制台中删除换行符
【发布时间】:2016-04-09 04:17:13
【问题描述】:

我有这个循环,但是当我在我的角色之后按回车键时,它会对其进行处理,然后在再次要求输入之前处理'\n'。请!!!!帮助

int input;



      while (true){
        input = getchar(); 
        fflush(NULL);
        input = input - '0';
        if( input != 'e' && input != '\n') {
            rc = state_fun(input);
        }

5[ENTER] 处理 5 作为输入,然后处理 10(即 ascii '\n')作为输入,然后再次请求输入。快把我逼疯了

【问题讨论】:

  • 在 while 循环的末尾添加一个虚拟 getchar() 以使用该 '\n'
  • 刷新标准输入的便携方式是int c; while((c = getchar()) != '\n' && c != EOF);fflush(NULL) 不会刷新 stdin,因为标准说 fflush(stdin); 是未定义的行为。
  • 您刚刚从input 中减去了'0'。之后,您针对e\n 测试该结果值,因此如果您按:,它将使条件为真
  • 您使用的是什么操作系统?

标签: c io getchar fflush


【解决方案1】:

你可以关闭控制台的回显功能,只回显不是'\n'的字符。如果你使用linux,你可以使用这个代码:

#include <termios.h>
#include <stdio.h>
#include <unistd.h>
int main(){
    struct termios old, new;
    int nread;

    /* Turn echoing off and fail if we can't. */
    if (tcgetattr (STDIN_FILENO, &old) != 0)
      return -1;
    new = old;
    new.c_lflag &= ~(ECHO|ICANON);
    if (tcsetattr (STDIN_FILENO, TCSAFLUSH, &new) != 0)
      return -1;

    char input;
    while (1)
    {
        input = getchar();
        if (input!='\n')
            putchar(input);
    }

    /* Restore terminal. */
    tcsetattr (STDIN_FILENO, TCSAFLUSH, &old);
}

请参阅Hide password input on terminal

【讨论】:

    【解决方案2】:
    int input;
    while(true) {
        input = getchar();
        getchar(); // <------
        fflush(NULL);
        input = input - '0';
        if( input != 'e' && input != '\n') {
            rc = state_fun(input);
        }
    }
    

    添加一个额外的getchar() 将解决您的问题。这是因为 5 Enterstdin 上放置了 2 个字符:'5''\n',您可能不会想到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      相关资源
      最近更新 更多