简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM