Thread: need help with simple while loop (newbie)

  1. #1
    Registered User
    Join Date
    Apr 2020
    Posts
    1

    need help with simple while loop (newbie)

    Code:
    #include <stdio.h>
    int main (void)
    {
    int it = 0;
    char ch;
    
    printf ("type a char");
    scanf ("%c", &ch);
    
    while ( ch != 'z' )
    {
    
    ++it;
    printf ("type the next char");
    scanf ("%c", &ch);
    }
    printf ("%d", it);
    
    return 0;
    }



    why does the it print type next char twice??????

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,729
    Because "%c" is special, in the way that it doesn't ignore whitespace. If you want it to, you need to add a space before the percent sign, like this:
    Code:
    scanf(" %c", &ch);
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Apr 2017
    Location
    Iran
    Posts
    101
    I made some changes to your code:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (void)
    {
        int it = 0;
        char ch;
     
        printf ("Type a char, 'q' to quit\n");
        scanf (" %c", &ch);
     
        while ( ch != 'q' ) // do while is possible too
        {
     
            ++it;
            printf ("Type the next char\n");
            scanf (" %c", &ch);
        }
            printf ("Number of entered chars is %d\n", it);
     
        return EXIT_SUCCESS;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. newbie Q. about do-while loop
    By kingkoks in forum C Programming
    Replies: 6
    Last Post: 07-12-2015, 10:04 AM
  2. Loop structures, please help a newbie
    By Helen Binet in forum Tech Board
    Replies: 5
    Last Post: 12-19-2011, 04:12 AM
  3. Newbie with a if loop problem.
    By Alpinstang in forum C Programming
    Replies: 6
    Last Post: 02-12-2010, 12:57 PM
  4. newbie: need help using malloc in a loop
    By happyclown in forum C Programming
    Replies: 11
    Last Post: 01-03-2009, 05:59 PM
  5. Help.. newbie for loop..stuck with the loop..
    By jochen in forum C Programming
    Replies: 15
    Last Post: 10-01-2007, 12:31 AM

Tags for this Thread