Chris K
Chris K

Reputation: 1576

How to read (small) integers from ASCII text files into adequate data arrays in C++

I want to load a bunch of integers from an ASCII text file (separated by a blank) knowing the data range a priori (e.g. 0-255). My problem is that I cannot read such numbers using the ">>" operator on my input stream where the right-hand side is of type "unsigned char". The data file may look like this:

12 42 0 127 255  

(Just in the case that this is important: There is a linebreak at the end but this editor seems to ignore it even though I have added two blanks.) And here is my sample code:

#include <cstdint>
#include <fstream>
#include <iostream>

using Datum = uint_least8_t; // Does not work.
// using Datum = unsigned char; // Does not work either (is "usually" the same as above).
// using Datum = char; // Does not work -- as expected. But why does this not store the blanks?
// using Datum = uint_least16_t; // Works.

int main()
{
  std::ifstream is( "data.txt", std::ifstream::in ); // not std::ifstream::binary
  constexpr std::size_t n = 5;
  Datum data[n];
  for( std::size_t i = 0; i < n; ++i )
    is >> data[i];

  for( std::size_t i = 0; i < n; ++i )
    std::cout << "\"" << data[i] << "\" ";
  std::cout << "\n";

  return 0;
}

With the first three typedefs the result is

"1" "2" "4" "2" "0"

So can anyone tell my why this happens, and how to fix it? I don't like the idea of having to store the numbers in a unnecesarily big data type (even just) temporarily.

Upvotes: 1

Views: 78

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385325

unsigned char is special — the standard library is applying its special-case "interpret and convert ASCII character" algorithm, so that reading "2" from the file will result in the unsigned char value 50, not 2.

This'll also be the case for any "types" which are actually only aliases of char or unsigned char, such as uint_least8_t (probably).

Read into an int instead, then convert down to unsigned char if you need to.

Upvotes: 2

Related Questions