Topic: Woes of Cin and Cout
Author: retterer@decatl.alf.dec.com (Rick Retterer)
Date: 30 Jun 1994 15:08:48 GMT Raw View
Hello,
I have just started to get involved with C++ and have run accross something
that I find confusing. Cin and Cout is giving me problems.
Example:
#include <iostream.h>
int main()
{
char name[20];
int age = 0;
cout << "Please enter your age: ";
cin >> age;
cout << "\n" << dec << age << ' ' << oct << age << ' ' << hex << age;
cout << "Please enter your name: ";
cin.get(name,20);
cout << name;
exit(0);
}
I compile this small program, that I copied from a book and tried to run
it, it will prompt me for my age, I enter it, it displays back my age in
decimal, octal, and hexidecimal. It then displays the line where it asks
my name and then terminates. It does not accvio, it just finishes.
Why is it not stopping and asking for my name?
I have tried this using Borland Turbo C++, MS-Visual C++, and Dec C.
Thanks
Rick R.
Author: admin@rzaix13.uni-hamburg.de (Bernd Eggink)
Date: 1 Jul 1994 08:37:34 GMT Raw View
Rick Retterer (retterer@decatl.alf.dec.com) wrote:
> Hello,
> I have just started to get involved with C++ and have run accross something
> that I find confusing. Cin and Cout is giving me problems.
> Example:
> #include <iostream.h>
> int main()
> {
> char name[20];
> int age = 0;
> cout << "Please enter your age: ";
> cin >> age;
> cout << "\n" << dec << age << ' ' << oct << age << ' ' << hex << age;
> cout << "Please enter your name: ";
> cin.get(name,20);
> cout << name;
> exit(0);
> }
> I compile this small program, that I copied from a book and tried to run
> it, it will prompt me for my age, I enter it, it displays back my age in
> decimal, octal, and hexidecimal. It then displays the line where it asks
> my name and then terminates. It does not accvio, it just finishes.
> Why is it not stopping and asking for my name?
Because after 'cin >> age', the next character in the input stream is the
newline. get() reads until it encounters a newline, which means, it
generates an empty string, and then stops. When switching from
operator>> to get(), first discard the rest of the input line including
the '\n' by calling
cin.ignore(INT_MAX, '\n');
> I have tried this using Borland Turbo C++, MS-Visual C++, and Dec C.
> Thanks
> Rick R.
--
+----------------------------------+
| Bernd Eggink |
| Rechenzentrum Uni Hamburg |
| admin@rzaix13.rrz.uni-hamburg.de |
+----------------------------------+