confused by Do While loop

This is a discussion on confused by Do While loop within the C Programming forums, part of the General Programming Boards category; Code: do{ _new=(node*)malloc(sizeof(node)); printf("enter the letter \n"); scanf("%c",&_new->ch); // the program don't stop in this part rear->next=_new; rear=rear->next; printf("another node\n"); ...

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    72

    Angry confused by Do While loop

    Code:
    do{
    		_new=(node*)malloc(sizeof(node));
    		printf("enter the letter \n");
    		scanf("%c",&_new->ch);	//    the program don't stop in this part
    		rear->next=_new;
    		rear=rear->next;
    		printf("another node\n");
    		scanf("%c",ans);
    	}while(ans!='n');
    ĘPlease help me and thanks in advance
    proud to be from aui www.aui.ma and also a great elton john's fan

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,761
    > scanf("%c",ans);
    Oops, no &
    Did you get any warnings from your compiler about this?
    Consider using gcc with the -Wall option to tell you about such things before running the code.

    Using %c is problematic since it takes the next character regardless. All the skip white space used by every other format is suppressed.

    So if you typed say "a" and return, then
    > scanf("%c",&_new->ch);
    This would get the 'a'
    > scanf("%c",ans);
    This would get the \n

    Pretty soon, you can find yourself out of step with the actual input, leading to the problems you describe.

    Consider using fgets() for ALL INPUT, then extract what you need from the returned buffer.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. My loop within loop won't work
    By Ayreon in forum C Programming
    Replies: 3
    Last Post: 03-18-2009, 11:44 AM
  2. While loop misbehaving (or misunderstanding)
    By mattAU in forum C Programming
    Replies: 2
    Last Post: 08-28-2006, 03:14 AM
  3. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 01:13 AM
  4. Loop, Loop, Loop?!
    By aprilbiz in forum C Programming
    Replies: 10
    Last Post: 07-24-2002, 05:45 AM
  5. How to change recursive loop to non recursive loop
    By ooosawaddee3 in forum C Programming
    Replies: 1
    Last Post: 06-24-2002, 09:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21