我需要使程序的方式,当返回键被输入,它继续与程序,并再次打印最初的行。
我试图用(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“,但我不知道如何绕过它。
发布于 2019-01-08 20:35:15
如何忽略输入中的'\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()。
https://stackoverflow.com/questions/54099154
复制相似问题