Thread: Problems with Getch() program execution order

  1. #1
    napKINfolk.com napkin111's Avatar
    Join Date
    Apr 2002
    Posts
    310

    Problems with Getch() program execution order

    I'm having problems with the getch() function. The following program executes like this:
    (type in "napKIN" then <enter>)
    (output)napKINHow do I make this appear before the input?

    I want it to say the text, then output the input.

    Here is my code:

    Code:
    #include <conio.h>
    #include <iostream.h>
    
    char text;
    
    int main()
    {
    	cout<<"How do I make this appear before the input?";
    	while ((text=getch()) != '\r')
    		cout<<text;
    	cout<<"\n"<<text;
    	return 0;
    }

    Could someone please tell me how to do this, please?

    napKIN

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Try this:

    cout<<"How do I make this appear before the input?" << flush;

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    In addition, C and C++ i/o streams may not be synchronised, which can lead to some surprises - like getting the same data twice.

    Choose an i/o mechanism and stick to it

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    After your first output statement, send endl to the cout stream as well. That automatically flushes the buffer.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Registered User Liam Battle's Avatar
    Join Date
    Jan 2002
    Posts
    114
    if you are going to be mixing I/O streams be used to problems like that alot...

    I suggest just use the IOSTREAM for minor output and input, else make your own I/O stream (thats what i do)
    LB0: * Life once school is done
    LB1: N <- WakeUp;
    LB2: N <- C++_Code;
    LB3: N >= Tired : N <- Sleep;
    LB4: JMP*-3;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 19
    Last Post: 05-30-2007, 05:47 PM
  2. Problems in a game program
    By ChronoSquare in forum C++ Programming
    Replies: 4
    Last Post: 06-08-2006, 07:32 AM
  3. Program calculation problems?
    By rebel in forum C++ Programming
    Replies: 7
    Last Post: 11-28-2005, 03:31 PM
  4. Problems with easy program
    By chuckster in forum C++ Programming
    Replies: 2
    Last Post: 09-09-2004, 11:08 AM
  5. randomizing order of execution of function
    By y2jasontario in forum C Programming
    Replies: 2
    Last Post: 04-03-2002, 07:50 PM