Reputation: 132
I am trying to read a single digit from a number stored in a text file. I have the following:
int main() {
int test;
std::ifstream inFile("testNum.txt");
test = inFile.get();
std::cout << test << std::endl;
}
The number in testNum looks something like 95496993 and I just want to read a single digit at a time.
When printing out the "test" variable I am getting the number 57 which is actually the ASCII number for the digit 9.
How can I get read the file to store the actual digit instead of the ASCII value?
I also tried casting to an int with int a = int(test)
but that did not work.
.
My end goal is to be able to read each digit of the number individually and store them somewhere separately.
Thank you.
Upvotes: 0
Views: 354
Reputation: 302
The typical C way of converting ASCII numbers to int
is to use something like
test=in.GetFile()-'0' // or use 48 instead of '0'
that way you end up with the number 9 as value for test
instead of 57.
Upvotes: 0
Reputation: 7344
Try to use:
char test;
Or:
std::cout << (char)test << std::endl;
std::cout encoding of data depends of the type of the element you want to output.
In this case you want to output '9' as an ASCII digit, and not 57 as its integer representation (char vs int).
Upvotes: 1