Hi I would like to read from a C++ file, but the problem is the file contains ints and chars. When theres a char I need to do one thing and when there's an int I need to do another. How can I differentiate between the ints and chars when reading in from the file??
C++ reading from a file
Collapse
X
-
Tags: None
-
here is a simple way
when you read the file char by char check if the ASCII value of the char is not in the range of numbers if it is not then save it in a char variable. if it is save it in a number.
for example
char c
read in(//some file)
c = get input
if (ASCII of c is not in the range of numbers)
add c to a char varible
else
convert c to a number and add it to an int varible
gppd luck
hsnComment
-
Here's what I would do. I would read the input as a string. Then attempt to convert the string to an integer. If the conversion fails, you don't have an int, so you must work with a string (which may be just a single character).
You can Google to find out how to read input in C++ as strings (using getline). Conversion is a pretty popular question as well. You can do things the C way or the C++ way. The C++ way involves stringstreams. The C way is best done with strtol.Comment
-
You differentiate between chars and ints in the same file becuse you know how they were written in the first place. Otherwise, you can't tell if this byte is a char or part of an int.Comment
Comment