cin.get() does not work if there is a previous cin?

From: Rusty Shackleford (johndoe_at_nospam.com)
Date: 07/31/04


Date: Sat, 31 Jul 2004 17:28:22 GMT

I typed this c++ program demonstrating the 'for' loop and added the
'cin.get()' to hold the dos console open for a keypress. The problem is it
does not work. The console disappears right after I input the number to
'cin'. If I comment out the first 'cin' then it works. If I use the
'system("Pause")' call it works also. I am wondering if this is not working
because the first call to 'cin' is buffered so the call to 'cin.get()'
thinks it already has a character? If that is so then how do you clear the
'cin' buffer? or mayber there is a bug in my compiler. Iam using DevC++
compiler which is a free compiler so maybe that is the problem?

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

#include <iostream>

using namespace std;

int main() {

   int sum = 0;
   int count = 0;

   cout << "How many integers do you want to sum? ";
   cin >> count;

   for(int i = 1;i <= count;i++)
      sum += i;

   cout << endl
        << "The sum of the integers from 1 to " << count
        << " is " << sum << endl;

   cin.get();
   return 0;
}

--------------
Rusty Shackleford

'What ever happens, happens necessarily'

mhaefner@NOSPAMsbcglobal.net

Remove NOSPAM from E-mail address to reply.



Relevant Pages

  • Re: Im a newb!!
    ... cin and cout are rather peculiar things. ... pre-assigned by the compiler before the compiler lets you get control of the ... You want output to go to a file instead of the monitor; ...
    (alt.comp.lang.learn.c-cpp)
  • Re: g++ problem
    ... Although #include <iostream> was entered before the ... start of main the g++ compiler did not recognize cin and cout. ...
    (Debian-User)
  • Re: a question about cin
    ... compiler says there is an error at "while (cin>>s)" line and it said that ... operand of type 'std::string' (or there is no acceptable conversion)" what should I do now???? ...
    (microsoft.public.vc.language)
  • gets and cin
    ... Compiler: g++ ... keyboard at least. ... When I delete line with cin it is working. ...
    (comp.lang.cpp)
  • Re: PR-Tree
    ... defines main to return an int. ... Not void, not string, not array of doubles. ... buffer, though I suspect the getch- also not part of C - might do that. ... and Turboc compiler or any windows compatible c language compiler) ...
    (comp.lang.c)