Welcome to the MacNN Forums.

If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

You are here: MacNN Forums > Software - Troubleshooting and Discussion > Developer Center > C loops

C loops
Thread Tools
Fresh-Faced Recruit
Join Date: Nov 2002
Status: Offline
Reply With Quote
Nov 8, 2002, 09:58 PM
 
I'm trying to learn C, and im having problems with a few loops. For example, I'll use my program that finds multiples of 6:

#include <stdio.h>

int main()
{
int i;
char ch;

/* display all multiples of 6 */
for(i=1; i<10000; i++){
if(!(i%6)){
printf("%d, more? y/n ", i);
ch= getchar();
if(ch=='n') break; /* stop the loop */
printf("\n");
}
}
}

Now it compiles cleanly, but something funny happens. The first time, the loop will function properly, now on the second time, (i think) it will skip the 'ch=getchar();' and then repeat again. The third time, it will function normally. And so on. The output looks like this.

6, more? y/n y

12, more? y/n
18, more? y/n y

24, more? y/n
30, more? y/n y

36, more? y/n
42, more? y/n n

Does anyone know why it doesn't ask for a character for the even loop iterations?
     
Dedicated MacNNer
Join Date: Nov 2000
Status: Offline
Reply With Quote
Nov 8, 2002, 10:27 PM
 
On 12, 24, and 36 it's getting the newline that's still in the input buffer.

Code:
ch=getchar(); getchar(); /* gobble up newline */
     
Fresh-Faced Recruit
Join Date: Nov 2002
Status: Offline
Reply With Quote
Nov 8, 2002, 10:30 PM
 
could you expand on that? please?
     
Admin Emeritus
Join Date: Oct 2000
Location: Boston, MA
Status: Offline
Reply With Quote
Nov 8, 2002, 11:39 PM
 
Originally posted by Spiffster:
could you expand on that? please?
When you input "y", what you're typing is {y} {return} which is "y\n".

You getchar the first time, which will retrieve the y, but the second time it retrieves the endline because that's still in stdin. You could getchar() again like the poster above mentioned or use fpurge(stdin) to clear the input buffer.
"Against stupidity, the gods themselves contend in vain" (Schiller)
     
Senior User
Join Date: Jun 2001
Location: Merry Land
Status: Offline
Reply With Quote
Nov 9, 2002, 04:19 PM
 
Couldn't you also use scanf instead of getchar?
     
   
Thread Tools
Forum Links
Forum Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Top
Privacy Policy
All times are GMT -5. The time now is 06:19 PM.
All contents of these forums © 1995-2011 MacNN. All rights reserved.
Branding + Design: www.gesamtbild.com
vBulletin v.3.8.7 © 2000-2011, Jelsoft Enterprises Ltd., Content Relevant URLs by vBSEO 3.3.2