简体   繁体   中英

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. 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> . 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) . Once I changed the %c to %s for string retrieval it fixed the problem.

I'm not certain but getString might fix your issue as I think it would do the same thing.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM