Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

reading numeric value to char

1 view
Skip to first unread message

Mikael Gustavsson

unread,
Feb 21, 2004, 6:00:08 AM2/21/04
to
I use characters to store numerical values and
I'm reading from a file that looks like this:
0 2 40 -2 ..

ifstream from("file");

for(int i=0; i<lines in file; ++i) {
from >> data[i].a >> data[i].b
>> data[i].c >> data[i].d;
}

a, b, c and d are characters used to store numerical values.
I want to read 2 as 2 not ascii '2', and i want 40 as 40, not '4' and '0'.

Yes, I can read into a temporary int, and cast. But is there a nicer way?

--
Mikael Gustavsson

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Jack Klein

unread,
Feb 22, 2004, 5:59:13 AM2/22/04
to
On 21 Feb 2004 06:00:08 -0500, mig...@fnatte.nada.kth.se (Mikael
Gustavsson) wrote in comp.lang.c++.moderated:

> I use characters to store numerical values and

Why? Unless you have an extremely large number of them, it makes much
more sense to use ints.

> I'm reading from a file that looks like this:
> 0 2 40 -2 ..

Are you using signed char or just plain char? On some implementations
plain char will be signed.

> ifstream from("file");
>
> for(int i=0; i<lines in file; ++i) {
> from >> data[i].a >> data[i].b
> >> data[i].c >> data[i].d;
> }
>
> a, b, c and d are characters used to store numerical values.
> I want to read 2 as 2 not ascii '2', and i want 40 as 40, not '4' and '0'.
>
> Yes, I can read into a temporary int, and cast. But is there a nicer way?

You haven't explained what the data in the file looks like. If you
created the file and put binary data in it, you should be able to read
binary data back. If the file contains numbers in text, somewhere
along the line you need to do the conversion, and in that case reading
into an int is probably the best solution.

But you do not need a cast to assign an int to a char. The conversion
is automatic. If the value of the int is outside the range of values
representable in the char, and the char is signed, the results are no
different with or without the cast.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html

0 new messages