[英]Input chars in separate lines in c
So I'm trying to implement a stack in c. 所以我试图在c中实现一个堆栈。 I wrote all the functions, but I have a problem with fgetc function. 我写了所有函数,但是fgetc函数有问题。 So here's a part of my code: 所以这是我的代码的一部分:
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 is a function i wrote that converts char to int. ctoi是我编写的将char转换为int的函数。 The problem is, if i enter, for exmple: 问题是,如果我输入,例如:
1
and press enter, the first call of the function will ask me for input, but the second one(inside the push function call) will automatically forward '\\n' as an argument, and I would like o ignore '\\n' and ask me for an input again. 然后按Enter键,该函数的第一个调用将要求我输入,但是第二个(在push函数调用内部)将自动转发“ \\ n”作为参数,我希望o忽略“ \\ n”并询问我再次输入。 Is this possible? 这可能吗? Thanks! 谢谢!
Each time Enter is hit, a '\\n' is left in stdin. 每次按下Enter键时 ,标准输入中都会留一个'\\ n'。 You can ignore it by #include <ctype.h>
and writing 您可以通过#include <ctype.h>
并编写忽略它
do {
option = fgetc(stdin);
} while(isspace(option));
I cannot, because the second call is an argument of another function. 我不能,因为第二个调用是另一个函数的参数。
Well, you can also write your own function for input: 好了,您也可以编写自己的输入函数:
int getOption(void)
{
int option;
do {
option = fgetc(stdin);
} while(isspace(option))
return option;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.