[英]While loop generating printf twice before asking for input?
For some reason this while loop executes twice and the strings are printed twice before it prompts for input. 由于某种原因,此while循环执行两次,并且在提示输入之前将字符串打印两次。 I had assumed it was that the input buffer had a character in it, but it does not to my knowledge.
我原以为输入缓冲区中有一个字符,但据我所知。 Any advice?
有什么建议?
while (count >= 0 && stop != 83 && isClosed == 0) {
printf("Percentage of Door Closed: %d\n",count);
count -= 10;
printf("If sensor detects object press 'S'\n");
printf("Press any button to continue closing door\n");
stop = getchar();
if (count == 0) {
isClosed=1;
}
}
Output: 输出:
Percentage of Door Closed: 100
If sensor detects object press 'S'
Press any button to continue closing door
Percentage of Door Closed: 90
If sensor detects object press 'S'
Press any button to continue closing door
a
Percentage of Door Closed: 80
If sensor detects object press 'S'
Press any button to continue closing door
Percentage of Door Closed: 70
If sensor detects object press 'S'
Press any button to continue closing door
S
You're picking up the newline character that gets sent to the input stream when you type S <Enter>
. 当您键入
S <Enter>
时,您将获取发送到输入流的换行符。 You can deal with this a couple of ways: 您可以通过以下两种方式处理此问题:
while ((stop = getchar()) == '\n'); // loops until it reads a non-newline
// character
or 要么
scanf(" %c", &stop); // note leading blank in format string; this tells scanf
// to skip any leading whitespace characters.
I had a similar problem today, since I didn't use getchar
to get my character and instead used scanf("%c", &stop)
. 我今天遇到了类似的问题,因为我没有使用
getchar
来获取我的角色,而是使用了scanf("%c", &stop)
。 Once I changed the %c
to %s
for string retrieval it fixed the problem. 一旦我将
%c
更改为%s
进行字符串检索,就解决了问题。
I'm not certain but getString
might fix your issue as I think it would do the same thing. 我不确定,但
getString
可能会解决您的问题,因为我认为它会做同样的事情。
Could be that you're starting the program with a key that also fills the buffer as some keys might generate several characters. 可能是你正在使用也填充缓冲区的键启动程序,因为某些键可能会生成多个字符。 Put a breakpoint at stop = getchar() and watch the value of stop when you step over it in the first iteration of the loop.
在stop = getchar()处放置一个断点,并在循环的第一次迭代中跳过它时观察stop的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.