Search code examples
c++ifstream

Reading digits from a file and storing them as decimal instead of ASCII in C++


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.


Solution

  • 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).