【发布时间】: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