 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Mikael Gustavsson Guest
|
Posted: Sat Feb 21, 2004 11:00 am Post subject: reading numeric value to char |
|
|
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
| Quote: | 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! ]
|
|
| Back to top |
|
 |
Jack Klein Guest
|
Posted: Sun Feb 22, 2004 10:59 am Post subject: Re: reading numeric value to char |
|
|
On 21 Feb 2004 06:00:08 -0500, [email]migu02 (AT) fnatte (DOT) nada.kth.se[/email] (Mikael
Gustavsson) wrote in comp.lang.c++.moderated:
| Quote: | 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.
| Quote: | 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.
| Quote: | 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
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|