【问题标题】:Input chars in separate lines in c在c中的单独行中输入字符
【发布时间】:2016-04-12 15:00:37
【问题描述】:

所以我试图在 c 中实现一个堆栈。我写了所有的函数,但是 fgetc 函数有问题。所以这是我的代码的一部分:

    while (1) {
    printf("Choose an option: \
            \n 1 Push \
            \n 2 Pop \
            \n 3 Top \
            \n 4 Print \
            \n 5 Exit\n");

    option = fgetc(stdin);
    opt = ctoi(option);

    while ( opt < 1 || opt > 5 ) {
        printf("Wrong entry, let's try again: \n");

        option = fgetc(stdin);
        opt = ctoi(option);
    }

    switch ( opt ) {
    case 1: push(&stack, fgetc(stdin)); break;
    case 2: pop(&stack); break;
    case 3: top(&stack); break;
    case 4: print_stack(&stack); break;
    case 5: return 0; break;
    default: printf("impossible"); break;
    }

}

ctoi 是我编写的将 char 转换为 int 的函数。问题是,如果我输入,例如:

1

然后按回车,第一次调用函数会要求我输入,但第二次(在 push 函数调用中)会自动转发 '\n' 作为参数,我想忽略 '\n ' 并再次要求我输入。这可能吗?谢谢!

【问题讨论】:

  • 所以比较它并忽略...
  • 我不能,因为第二个调用是另一个函数的参数。
  • 你可以修改你的逻辑,你知道的......

标签: c input fgetc


【解决方案1】:

每次 Enter 时,标准输入中都会留下一个“\n”。您可以通过#include &lt;ctype.h&gt; 和写作忽略它

do {
    option = fgetc(stdin);
} while(isspace(option));

我不能,因为第二个调用是另一个函数的参数。

好吧,你也可以编写自己的输入函数:

int getOption(void)
{
    int option;
    do {
        option = fgetc(stdin);
    } while(isspace(option))
    return option;
}

【讨论】:

    猜你喜欢
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    相关资源
    最近更新 更多