We help IT Professionals succeed at work.

cin>>flush

gutta_naveen
gutta_naveen asked
on
4,574 Views
Last Modified: 2012-06-27
i am running my C++ program in LINUX redhat 9
i got actually 2 questions

question 1
---------------
  my code looks like

         char buf[20] = " ";
         while(1)
         {
                cin>>flush;
                cout<< " enter the today's date " ;
                cin>>ws;
                cin.get(buf,20,'\n');
          }

   i wrote makefile to run the code and at runtime it goes into infinite loop like

              enter the today's date
              enter the today's date
              enter the today's date
              enter the today's date
 
      when i remove cin>>flush it is fine...........can anyone solve my problem..thanks

question 2
------------
same code after removing cin>>flush  .. i am having one more problem/error

          char buf[20] = " ";
         while(1)
         {
                cout<< " enter the today's date " ;
                cin>>ws;
                cin.get(buf,20,'\n');

                if( )
                {
                        ....
                        cout<<"date stored in the file"<<endl;
                 }
                 else
                 {
                                cin.clear()
                                cout<<"invalid date "<<endl;
                   }
          }

          }

       when it prompt's me to enter date ... at runtime it looks like

 output:
         enter the today's date  2 8 2004

                        invalid date

           enter the today's date

            date stored in the file

------------------------

it says invalid date and prompt me to enter the date again ... BUT before i enter it takes
the previously entered date ( and stores it in file ) and goes ahead into the next step

point sto remember

-- running the program in linux using makefile and the compiler is g++
                                     ------          ---------                             -------
thanks a lot in advance


             
               
Comment
Watch Question

CERTIFIED EXPERT

Commented:
If I'm not mistaken, you cannot flush in input stream. When I try this on my system, the compiler complains about the line cin>>flush. Which compiler version are you using (gcc -v will print this information). You don't need this line.

What is the condition in your if () statement? You cannot leave the condition empty.

Author

Commented:
i am using g++ compiler  .. there were errors when i used gcc...by the way  i got solved my second question...... i included cin.clear() before cin.get() and it worked fine............ BUT still waiting for question 1........

  By the way what is the difference between
 
  cin>>flush   and    cin.clear()

aren't  both clearing the input  buffer .... can anyone describe the difference

 one more question ......... how do you make sure there is no memory leak in your program

one more ...i took my program from windows and running it under linux............so what are the things i got to remember in mind to make sure there are no problems or errors when i run under LINUX

i  appreciate your help
CERTIFIED EXPERT

Commented:
What version of the compiler are you using? Use the -v parameter to get this information.

Commented:
-->>           cin >> flush ;

The flush manipulator u are using isn't valid for a istream (i.e. for cin) type of object

The flush manipulator is defined for ostream class

Look at the following link

http://www.cplusplus.com/ref/iostream/ostream/_flush.html

And regarding flushing you input stream [for newline charracter] (since u are using get in while loop)

use cin.ignore ( )

Look at the following reference

http://www.cplusplus.com/ref/iostream/istream/ignore.html



Amit


CERTIFIED EXPERT

Commented:
Thanks Amit for confirming my comment. And because of that, the compiler should output an error message.
>               if( )
 >               {
 >                       ....
 >                       cout<<"date stored in the file"<<endl;
 >                }
 >                else
 >                {
 >                               cin.clear()
 >                               cout<<"invalid date "<<endl;
 >                  }
 
if you don't tell us, what condition your if() has, we cannot really help you.

In my opinion, clearing the input stream generally doesn't make much sense. Better take a buffer that is big enough to handle any reasonable inputs. I wouldn't even use that 'eatwhite' feature of istream as you have to analyze the input buffer anyhow. I suppose, that if you remove cin.clear() your program will wait after prompt as you would expect it.

Regards, Alex

Author

Commented:
hi sys_prog
 after going thru link and reading it .... i was clear...thanks
and i was not that clear in explaining my code or problem ... i mean to say i am not worried about the newline character....i think once i enter the data at the prompt which is read into "buf" variable is first  read into memory buffer which is what i want to clear ( that's how it works right  ? that's what i understood from the error) and i think cin.clear() does ................

hi itsmean...

        don't worry about the if condition.. i am calling some method which will validate the "buf" variable and.....if i remove the cin.clear() it says invalid date ( even though i enter valid date) and again prompt me to enter the date..but before i enter it will say date stored in the file......look at my output which i posted in my question you will understand
CERTIFIED EXPERT

Commented:
If you want help, please answer the questions of the experts. It is important what you use as your if condition. You are apparently using syntactically wrong constructs that your compiler does not report as errors, therefore it is important what compiler version you are using.
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Commented:
Forgot to mention that
In the above code, I have to use cin.ignore () otherwise it runs in infinite loop

Amit

Commented:
Diffrenece between clear() and ignore()

clear ()
     Sets a new value for the control state ignoring the existing value.
     
     Look at following link
     http://www.cplusplus.com/ref/iostream/ios/clear.html    

ignore()
     Ignores rest of the characters from stream [depending on your parameter values]
     See the link I previously posted
     

HTH
Amit

Author

Commented:
ok khremer.......here is my code looks like

---------------
                char buf[20] = " ";
                cout<< " enter the today's date " ;
 
               cin.clear();                  

                cin>>ws;
                cin.get(buf,20,'\n');
               
                cout<<"buf value is "<< buf <<endl;

                if(split(buf))
                {
                        ....
                        cout<<"date stored in the file"<<endl;
                 }
------------------

 after cin.get() ..i am trying to print "buf" value but it is printing nothing if i remove cin.clear() function before cin.get()............... what happening in if() condition is as i said before it is calling a method split(buf) taking buf as input parameter and returns true or false...but before
if() condition i am trying to print "buf" variable which is printing null.........so the value entered itself is not read into "buf" variable...all these will get solved if i keep cin.clear() before cin.get()..........Do you still want to know more about the If() condition and the split(buf) method which i am calling

       
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Commented:
Hi gutta_naveen

The code u posted (without cin.clear()) should work

Try this code at your side,
This code works fine
If u remove cin >>ws , it would run in infinite loop


int main(int argc, char *argv[]) {
      char temp[5] = "" ;
      while ( 1 ) {
            cout << endl << "Enter 1 Number to exit : "  ;
              cin >> ws ;
            cin.get ( temp, 4, '\n' ) ;
            cout << endl << temp ;
            if ( temp[0] == 'a' ) {
                  cout << endl << "done" ;
                  break ;
            }
            else {
                  cout << endl << "Invalid value" ;                       
            }            
      }      
    system("PAUSE");    
    return 0;
}    


Amit

Author

Commented:
thanks everybody....
i was still waiting for suggestions/guidance  for my other questions which i posted at the end of my question

  i have copy pasted them here once again.............

 1 -  one more question ......... how do you make sure there is no memory leak in your program

 2 -  one more ...i took my program from windows and running it under linux............so what are the things i got to remember in mind to make sure there are no problems or errors when i run under LINUX

i  appreciate your help
CERTIFIED EXPERT

Commented:
1. To check for memory leaks you would use a tool like Valgrind (http://valgrind.kde.org/)
2. Depends on what you used on Windows. For example, there is no MFC in Linux. As long as you used just standard C++ features, you should be fine.I think most of the potential problems will be flagged by the compiler (no DWORD, ...)

Commented:
No comment has been added lately, so it's time to clean up this question.
I will leave the following recommendation for this question in the Cleanup topic area:

Split: Sys_Prog {http:#10329304} & khkremer {http:#10380810}

Please leave any comments here within the next four days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

Tinchos
EE Cleanup Volunteer

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.