GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 09-May-2007, 02:55
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 482
Peter_APIIT can only hope to improve
Angry

Keyboard Buffer Question


Hello all programmer, how to flush keyboard buffer in C++. In c, we can flush the keyboard buffer with this method : fflush(stdin);

How to flush keyboard buffer or fixed my program ?
CPP / C++ / C Code:
#include<iostream>
#include<string>

using namespace std;

int main(int argc, char *argv[])
{
/*	string string1,*/string astring;
	
/*	
	cout << "Enter a string : ";
	cin >> string1;
	cout << "The string is " << string1;
	// This will a string with any space
	
	
*/	int number;
	cout << "Enter a integer : ";
	cin >> number;
	cout << number;
	while(1)
	{
		cout << "\n\nEnter a string : ";
		getline(cin,astring);
		cout << astring;
	}
	return 0;
}

Please help me. Thanks for your help.
Last edited by LuciWiz : 09-May-2007 at 06:41. Reason: Please insert your C/C++ code between [cpp] & [/cpp] tags
  #2  
Old 09-May-2007, 07:56
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,720
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Keyboard Buffer Question


Quote:
Originally Posted by Peter_APIIT
Hello all programmer, how to flush keyboard buffer in C++. In c, we can flush the keyboard buffer with this method : fflush(stdin);
It's not Standard C, although it works with some compiler implementations.

Here's an easy way, assuming that the user entered a valid integer:
CPP / C++ / C Code:
	cout << "Enter an integer : ";
	cin >> number;
        while(cin.get() != '\n') // an "empty loop" to flush stdin buffer
            ;

If the user enters something that can't be converted to an integer, the program hangs up, since cin will be in a "fail" state and nothing else can be done with cin until the error flag is cleared. (You should always test for valid input anyhow, in my opinion.)

CPP / C++ / C Code:
	cout << "Enter an integer : ";
	cin >> number;
        if (cin) {
            cout << "You entered " << number << endl;
        }
        else { // can't do anything else with cin until error flag is cleared
            cout << "Invalid entry" << endl;
            cin.clear();
        }
        while(cin.get() != '\n') // an "empty loop" to flush stdin buffer
            ;


Regards,

Dave
  #3  
Old 10-May-2007, 02:52
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 482
Peter_APIIT can only hope to improve
Thumbs up

Re: Keyboard Buffer Question


My lecturer has told me before when we scan a character from user, the enter key will go in to keyboard buffer. This will cause next statement undefined behavior.

By the way, any standard C++ function to do so ?

Thanks for your help.
Your help is greatly appreciated by me and others.
  #4  
Old 10-May-2007, 07:53
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,720
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Keyboard Buffer Question


Quote:
Originally Posted by Peter_APIIT
My lecturer has told me before when we scan a character from user, the enter key will go in to keyboard buffer.
This is "normal" behavior for operating systems and C/C++ programs' interfaces to keyboard input: Whatever the user types goes into a buffer. When a program asks for input, it gets nothing until the user hits the 'Enter' key. Then stuff becomes available to the program.

Quote:
Originally Posted by Peter_APIIT
This will cause next statement undefined behavior.
Huh? What "next statement?" There is no undefined behavior in the snippet that I posted. Sometimes you must be aware of the presence of the newline and sometimes not. It depends on what method is used for the next program input statement.

By the way, there is a difference between "undefined behavior" and "misuse of functions that results in incorrect values and/or incorrect program operation."

Using fflush(stdin) results in "undefined behavior", since the C standard defines a standard library function, fflush(), that is used for output streams, but does not mention anything about flushing input streams. Microsoft compilers may very well do what you want (that is: empty out the input buffer, including the newline). Other compilers may not (and, in my experience, Borland and GNU compilers do absolutely nothing if you fflush(stdin)).

On the other hand, using cin>> to get an integer and then using getline() for the next input (expecting to get a string from the next line of user input) is not undefined behavior. It's a program bug that can be handled easily in a number of ways, all of which are Standard C++ and none of which result in undefined behavior. I gave an example.

Quote:
Originally Posted by Peter_APIIT
By the way, any standard C++ function to do so ?
To do what? Get stuff from user input (standard input from keyboard)? Standard C++ programs use the istream "cin" to get things from keyboard input. Overloaded extraction operator '>>' and various member functions and other functions get keyboard input:

Some examples using standard C++functions and operators:

CPP / C++ / C Code:

cin >> xyz; // for built-in data types and for objects of user classes
            // that have defined an overloaded extraction operator
c = cin.get(); // for chars
getline(cin, str); // for std::string objects
cin.getline(line, sizeof(line)); // for char arrays

Regards,

Dave
Last edited by davekw7x : 10-May-2007 at 09:04.
  #5  
Old 10-May-2007, 23:12
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 482
Peter_APIIT can only hope to improve

Re: Keyboard Buffer Question


Sorry for my stupidness. I don't know how to ask a smart question. I think i need to check the Eric Raymond's articles.


By the way, thanks very much.

Hope GOD will blessed you.
  #6  
Old 10-May-2007, 23:40
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,720
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Keyboard Buffer Question


Quote:
Originally Posted by Peter_APIIT
I think i need to check the Eric Raymond's articles.
As much as I admire and respect Eric Raymond as a person and an author, I'm not sure what he has published about stdin and input buffers that might clear up the confusion.

Regards,

Dave
  #7  
Old 12-May-2007, 21:00
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 482
Peter_APIIT can only hope to improve

Re: Keyboard Buffer Question


He has published some articles about how to ask a smart question.

You can check at his homepage.
Besides that, i also quite admire you because you willing to help people and clear the confusion inside my mind.

My hotlink account is peter_wkc_20@hotmail.com .

Thanks for your reply.

Hope GOD will blesses you.
  #8  
Old 18-May-2007, 02:52
Peter_APIIT Peter_APIIT is offline
Regular Member
 
Join Date: May 2007
Location: Malaysia
Posts: 482
Peter_APIIT can only hope to improve
Thumbs up

Re: Keyboard Buffer Question


CPP Code :
CPP / C++ / C Code:
/* A program that record employee detail 
   and connect to SQL server to future use
*/

#include<iostream>
#include<string>

using std::cout;
using std::endl;
using std::cin;
using std::string;
using std::getline;

#include "Employee.h"

int main(int argc, char *argv[])
{
    int loop;

    cout <<"\n\n\t\t  ";
    loop = 0;
    while(loop < 40)
    {
        cout << "-";
        loop++;
    }
    cout << "\n\n\t\t\tWelcome to Employee Detail System\n";
    cout <<"\n\t\t  ";
    loop = 0;
    while(loop < 40)
    {
        cout << "-";
        loop++;
    }
    Human *wong = new Human();
    

//    wong->setFirstName();
//    wong->setLastName();
//    wong->setAddress();

    Employee *peter = new Employee();
    peter->setEmployeeID();

    delete wong;
    delete peter;

    return 0;
}

void Human::setFirstName()
{
    cout << "Enter first name : ";
    cin >> firstname;
}

void Human::setLastName()
{
    cout << "Enter Last Name :";
    cin >> lastname;
}

void Human::setAddress()
{
    cout << "Enter the Address : ";
    cin.clear();
//    while(cin.get()!=(int)"\n"){getline(cin, address);}
    
}
void Employee::setEmployeeID()
{
    cout << "Enter Employee ID : ";
    cin >> employeeID;
};

Header File :
CPP / C++ / C Code:
// A header file for Employee

#ifndef _Employee_
#define _Employee_

#include<string>
using std::string;

class Human
{
protected:
    string firstname;
    string lastname;
    string address;
// The protected member can be accessed 
// from derived class member function
public:
    Human() : firstname(), lastname(), address(){}
    Human(string, string, string){}
    virtual ~Human(){}
    
    void setFirstName();
    string getFirstName();

    void setLastName();
    string getLastName();

    void setAddress();
    string getAddress();
};

class Employee : public Human
{
    int employeeID;
    float salary;
public:
    Employee() : employeeID(0), salary(0)
    {
        setFirstName();
        setLastName();
        setAddress();
    }
    ~Employee(){} 

    void setEmployeeID();
    int getEmployeeID();

    void setSalary();
    float getSalary();
};

#endif

The same problem which after Enter name, it just directly went to Enter employee ID. How i clear the next line buffer ?

The previous of the user enter is not integer. I have cast it.

Thanks for your help.

Your help is greatly appreciated by me and others.
Last edited by admin II : 18-May-2007 at 14:35. Reason: Please surround your CPP code with [CPP] ... [/CPP]
  #9  
Old 18-May-2007, 20:57
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,245
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: Keyboard Buffer Question


Don't use cin when reading a mix of strings and numbers. Use getline() and verify the input before using.

The problem you're having is cin is leaving your input buffer dirty because it reads only what it wants. getline() will always read the entire line entered. You just have to delete the '\n' at the end of the line read. And if you just read number, convert it from a string using any way that makes sense (stringstreams, sprintf, atoi, etc.)
__________________

Age is unimportant -- except in cheese
  #10  
Old 06-Oct-2008, 02:59
thecoolguy98 thecoolguy98 is offline
New Member
 
Join Date: Oct 2008
Posts: 1
thecoolguy98 is on a distinguished road
Thumbs up

Re: Keyboard Buffer Question


Quote:
Originally Posted by Peter_APIIT
How to flush keyboard buffer or fixed my program ?


its simple : use std::cin.sync().

CPP / C++ / C Code:

        int number;
	cout << "Enter a integer : ";
	cin >> number;
	cout << number;
	while(1)
	{
		cout << "\n\nEnter a string : ";
	        cin.sync(); //this gets rid of whatever is in the input buffer
		getline(cin,astring);
		cout << astring;
	}
	return 0;
}

 
 

Recent GIDBlogPython ebook by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Buffer size in C dereliction C Programming Language 3 05-Feb-2007 17:51
question about inline function bchasco C++ Forum 1 22-Jul-2005 15:52
non-member function question crq C++ Forum 1 03-Feb-2005 21:59
Bounded Buffering? pablowablo C Programming Language 0 17-Jan-2005 05:51
Repetition structure problem and question brookeville C++ Forum 17 29-Oct-2004 17:48

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 17:08.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.