在c中的单独行中输入字符

Input chars in separate lines in c

所以我正在尝试用 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' 并再次要求我输入。这可能吗?谢谢!

每次按 Enter 时,都会在标准输入中留下一个“\n”。您可以通过 #include <ctype.h> 和写作

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

I cannot, because the second call is an argument of another function.

嗯,你也可以自己写一个输入函数:

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