Thread: do while

  1. #1
    Microsoft. Who? MethodMan's Avatar
    Join Date
    Mar 2002
    Posts
    1,198

    do while

    I am using a do while loop to read input using scanf and putting each char into an array slot, and i want to stop when the person hits the return key

    Code:
    main()
    {
            char input[MAX];
            char ch;
            int i = 0;
            
            printf("Enter input:\n"); 
            
            do
            {
                    scanf("%c", &input[i]);                  
                    i++;
            }
            while(input[i] != '\n');
    }
    why doesnt this work, does the while stament not recognize the incremnet of i?

    Thanks

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >while(input[i] != '\n');
    You increment i before testing the value, this test reads the element after the one you just placed a value in, so the loop will never be true unless you get really lucky. This should work better:
    while ( input[i - 1] != '\n' );

    -Prelude
    My best code is written with the delete key.

  3. #3
    Microsoft. Who? MethodMan's Avatar
    Join Date
    Mar 2002
    Posts
    1,198
    Thanks..

  4. #4
    Idiotman
    Guest
    Uhh; not to mention the scanf only ends with a enter key being pressed. use getch() or getche() for single char input...

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Uhh; not to mention the scanf only ends with a enter key being pressed.
    No, scanf ends whenever you tell it to (in theory). If you say to read one character yet enter ten, scanf will read one character and then another upon the next iteration of the loop. I believe you are mistaking how scanf actually processes input with how the buffer handles input.

    >use getch() or getche() for single char input...
    Or not, getch and getche are nonstandard functions which may not exist on all implementations. getc, fgetc, and getchar will all work just as nicely and still be portable.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed