如何防止 '\n' 作为输入传递?
How to prevent '\n' being passed as input?
当我们执行下面的代码时:
#include <stdio.h>
int main(void){
char x,y;
scanf("%c", &y);
x = getchar();
putchar(x);
return 0;
}
在scanf("%c", &y);
语句中输入的输入被传递给x。有什么办法可以解决这个问题吗?我现在如果我们使用 scanf
那么我们可以通过 scanf("%*c%c", &x);
忽略 \n
但不知道在使用 getchar()
.
时会做什么
这基本上是输入缓冲区的问题,在您的情况下,您可以使用带有 fflush(stdin) 的替代输入字符串 getchar();用于处理此问题。
你可以这样做
#include <stdio.h>
int main(void)
{
char x,y,ch;
scanf("%c%*c", &y);
while((ch=getchar())!='\n'&&ch!=EOF); //removes all character in input buffer
x = getchar();
putchar(x);
return 0;
}
当我们执行下面的代码时:
#include <stdio.h>
int main(void){
char x,y;
scanf("%c", &y);
x = getchar();
putchar(x);
return 0;
}
在scanf("%c", &y);
语句中输入的输入被传递给x。有什么办法可以解决这个问题吗?我现在如果我们使用 scanf
那么我们可以通过 scanf("%*c%c", &x);
忽略 \n
但不知道在使用 getchar()
.
这基本上是输入缓冲区的问题,在您的情况下,您可以使用带有 fflush(stdin) 的替代输入字符串 getchar();用于处理此问题。
你可以这样做
#include <stdio.h>
int main(void)
{
char x,y,ch;
scanf("%c%*c", &y);
while((ch=getchar())!='\n'&&ch!=EOF); //removes all character in input buffer
x = getchar();
putchar(x);
return 0;
}