【问题标题】:How to ignore the '\n' character in the input如何忽略输入中的 '\n' 字符
【发布时间】:2019-06-03 13:54:53
【问题描述】:

我需要使程序在输入返回键时继续执行程序并再次打印初始行。

我尝试使用 (case '\n') 解决它,但没有成功,我尝试了一些 getchar() 变体,但遇到了同样的问题。

    void main()
{
char nameA[100];
char nameB[100];
char command;
int height;
int quit = 1;

struct node *ring1 = NULL;
struct node *ring2 = NULL;

while(quit)
{
    printf("command? ");
    scanf("%c", %command, 1);
    
    switch (command)
    {
        case 'q':
            printf("bye\n");
            quit = 0;
            break;
            
        case 't':
            printf("name? ");
            scanf(" %[^\n]", nameA);
            printf("height? ");
            scanf(" %d", &height);
            
            ring1 = insert_tail(ring1, nameA, height);
            break;
            
        case '\n':
            break;
        
        default:
            break;
    }
}

}

我希望能够打印的是

命令?

命令? ...

问题是,如果我使用“%c”,我将忽略新行,如果我使用“%c”,输出将如下所示:

命令?

命令? ...

但如果我在代码中使用 't' 命令,结果将如下所示

命令? t

名字?珠穆朗玛峰

身高? 8848

命令?命令?

我该如何解决?我认为问题是因为我实际上输入了两个字符,“t”和“\n”,但我不知道如何解决这个问题。

【问题讨论】:

  • scanf("%c", %command, 1); 退出不正确。试试scanf("%c", &command);
  • 可能会使用scanf("%c%*[^\n]%*c", & command),但它看起来很糟糕并且可能会失败
  • @anatolyg scanf("%c%*[^\n]%*c", & command) 输入"t\n" 将在stdin 中留下'\n' 以进行下一次scanf() 通话。当"%*[^\n]" 失败时,不使用"%*c"

标签: c while-loop scanf


【解决方案1】:

如何忽略输入中的'\n'字符

在所有命令之后,除了 '\n' 之外的所有命令都会消耗该行的其余部分。

t 的情况下,导致问题的是输入height 之后的'\n'。在寻找新命令之前使用它。

while(quit) {
    printf("command? ");
    scanf("%c", &command);
    switch (command) {
      ...
    }
    if (command != '\n') {
      int ch;
      while ((ch = getchar()) != `'\n'`) && (ch != EOF)) {
        ;
      }
    }
}

提示:考虑使用fgets() 进行用户输入,避免使用scanf()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多