cin char

J

jraul

Hi,

If you cin >> x, where x if of type char, and you input a number 7, it
will read the char '7'. However, char's are really integer types, so
is it possible to set a flag so that you can input an integer that
will fit in the range of a char (say 100)? I don't think so, but just
checking.
 
I

Ian Collins

jraul said:
Hi,

If you cin >> x, where x if of type char, and you input a number 7, it
will read the char '7'. However, char's are really integer types, so
is it possible to set a flag so that you can input an integer that
will fit in the range of a char (say 100)? I don't think so, but just
checking.
No. A char is a char.
 
M

Mike Wahler

jraul said:
Hi,

If you cin >> x, where x if of type char, and you input a number 7,

What is really input is the character '7'. All stream operations are
done as characters.
it
will read the char '7'.
Yes.

However, char's are really integer types,

Type 'char' is one of the integer types, yes.

so
is it possible to set a flag so that you can input an integer that
will fit in the range of a char (say 100)?

You can ask that a stream convert a sequence of input digit characters
to an integer; use the proper overload:

int i;
std::cin >> i;

You can determine whether this integer object's value is within
type 'char's range:

if(i >= std::numeric_limits<char>::min() &&
I don't think so, but just
checking.

If you describe more specifically what you're trying to do,
perhaps we can offer better advice.

-Mike
 
W

weihan

Hi,

If you cin >> x, where x if of type char, and you input a number 7, it
will read the char '7'. However, char's are really integer types, so
is it possible to set a flag so that you can input an integer that
will fit in the range of a char (say 100)? I don't think so, but just
checking.

You may try to define your own manipulator, such as :

struct Charint {
istream *fin ;
};

Charint& operator >> ( istream& in , Charint& foo ) {
foo.fin = &in ;
return foo ;
}

istream& operator>> ( Charint& foo , char & c ) {
int s ;
*(foo.fin) >> s ;
c = static_cast<char>(s) ;
return *(foo.fin) ;
}


int main() {
Charint charint ;
char c ;
cin >> charint >> c ;
cout << static_cast<int>(c) << endl ;

cin >> c ;
cout << static_cast<int>(c) << endl ;

return 0 ;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top