Thread: Doubt

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    Doubt


    I want output in following format:

    Enter the full name: Rim John
    John, Rim

    Please help me my program goes to infinite loop and only prints last name


    #include<stdio.h>
    #include<conio.h>

    int main(void)
    {
    clrscr();
    char ch1,ch2='a';
    printf("Enter the full name ");
    scanf(" %c",&ch1);

    while(getchar()!=32);//waits for space bar to be pressed
    while(ch2 != ' ')
    {
    scanf(" %c", &ch2);
    printf("%c",ch2);

    }
    printf(", %c",ch1);

    getch();
    return 0;
    }
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    1. Use [code][/code] tags when posting code.

    2. scanf(" %c", &ch2);
    Remove the leading space. You're forcing %c to read the next non-space character each time, not the next character.

    Also, reading the first name will need more work - but you'll see that soon enough.
    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

IMN logo majestic logo threadwatch logo seochat tools logo