Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hello;
I have this simple code:int a;
cin >> a;
cout << a;if I enter a char (r) instead of an int (23) I get a
whole number : 3154592
I know that i'm entering a wrong variable type, but
can any one explain what's going behind the
scene??
thanks.

I know that Perl automatically converts non-numerical characters to zero when working with numbers...maybe this is doing similar?

something like
cin >> a;
if(cin.fail())
{
cin.clear(1);
cin.ignore(80);
}Does some error checking. Once stream errors occur, you need to reset the fail bit before other operations can be done. The underlying cause is most likely the way the data types are represented at the machine level, but I'm not positive.
You can reduce stream errors by using char types for numerical input, and then convert them using strtol, strtod, etc.

Or you could change a to a character array.
Not a great example but it works:
char a[5];
int num;
bool usenum = false;
cin >> a;
if (a[0] >= '0' && a[0] <= '9')
{
usenum = true;
for (int i = 0; i < strlen(a); i++)
{
num *= 10;
num += a[i] - '0';
}
}
if (usenum == false)
cout << a;
else
cout << num;

This may or may not help, but extractors,
inserters, and other overloaded operators
from the iostream lib are probably not
returning the value of the correct type. It
may be as simple as no implicit
conversion to a char (in which case you
would have to explicitly
downcast it using a static cast
(depending on the compiler you are
using.)) It may also be a decimal
representation of the address of a
uninitialized char or void pointer to
returned to cout (depending upon which
overloaded function is called
iac with how your overloaded left/right
shift operators are defined.)You may also want to look at the behavior
of the derived 'ostringstream' definition of
class 'ios' in the iostream lib for your
compiler.Eric

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |