How to read byte and save ASCII byte value in integer in C ++

I have a simple question that bothers me.

Purpose : I want to read a given byte from a file (say, the first byte) and make int x the ASCII value of that byte. So, for example, if the byte / character is "a", I want x to be 97 (= 61 in hexadecimal format). I have the following reading the first byte of the example.txt file:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
  unsigned int x;
  unsigned char b;
  ifstream myFile ("example.txt", ios::out | ios::binary);
  myFile.seekg (0, ios::beg);
  myFile >> b;
  x = (unsigned int)b;
  cout << hex << x;
  return b;
}

Problem . If the first byte is represented by 08, then I really get the output from 8. But if the byte is represented by 09, then I get 0. I noticed that I look to get the next byte if this byte is also not 09. I don't know if my problem is only when the byte is represented in ASCII at 09.

. , ( ) int ASCII ?

( Windows XP)

+5
3

.

 myFile >> noskipws >> b;
+3

:

  • , . , , .
  • , ios::in ( ios::out).
  • noskipws, .
  • ? (, , ).

4- HEX :

#include <iostream>
#include <fstream>
#include <stdlib.h>

using namespace std;

int main() {

    ifstream myFile("<path>\\example.txt", ios::in | ios::binary);

    if (myFile) {

        unsigned char b;
        myFile.seekg(3) >> noskipws >> b;

        if (myFile) { // File was long enough?
            unsigned int x = b;
            cout << hex << x;
            return EXIT_SUCCESS;
        }

    }

    return EXIT_FAILURE;

}

( <path> .)

+3

Try reading with ifstream::readinstead operator>>. This worked for me:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){
  unsigned int x;
  unsigned char b;
  ifstream myFile ("example.txt", ios::out | ios::binary);
  myFile.seekg (0, ios::beg);
  myFile.read(reinterpret_cast<char*>(&b), sizeof(b));
  x = (unsigned int)b;
  cout << hex << x;
  return b;
}
+2
source

All Articles