Results 1 to 4 of 4

Thread: Out of order

  1. #1

    Thread Starter
    PowerPoster sail3005's Avatar
    Join Date
    Oct 2000
    Location
    Chicago, IL, USA
    Posts
    2,340
    why does the getch() run first no matter what? How can i make the getch run after i say like "enter a key"

    Code:
    #include <conio.h>
    #include <iostream.h>
    
    int get;
    
    int keypress(){
    
    	get = getch();
    
    
    	return get;
    
    }
    
    void main(){
    
    	cout<<"Press a key\n";
    	keypress();
    	cout<<get<<"\n";
    }

  2. #2
    Guest
    try this:


    Code:
    #include <conio.h>
    #include <iostream.h>
    
    int get;
    
    int keypress(){
    
    	get = getch();
    
    
    	return get;
    
    }
    
    void main(){
    
    	cout<<"Press a key\n";
                    flush(cout);
    	keypress();
    	cout<<get<<"\n";
                    flush(cout);
    }
    alternatively, you can do this:

    Code:
    #include <conio.h>
    #include <iostream.h>
    
    int get;
    
    int keypress(){
    
    	get = getch();
    
    
    	return get;
    
    }
    
    void main(){
    
    	cout<<"Press a key" << endl;
    	keypress();
    	cout<<get<<endl;
    }
    endl sends a new line, and flush's the output buffer, ensuring everything displays correctly.

  3. #3
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Because when you send something to any output device, it is nearly always buffered. So, you tell it to send the string, and it then waits for the key. When your program finishes, it flushes the buffers and prints it out.

    So to fix this, use "endl", which is the same as a newline and a buffer flush:
    Code:
    #include <iostream.h>
    #include <conio.h>
    
    void main() {
        cout << "Press a key" << endl;
        cout << getch() << endl;
    }
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  4. #4
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    Oh...hehe...

    Beaten by 2 minutes...
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width