如何读取字节并在c ++中保存整数字节的ASCII值 [英] How to read a byte and save ASCII value of byte in integer in c++

查看:117
本文介绍了如何读取字节并在c ++中保存整数字节的ASCII值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,让我很困惑。

I have a simple question that is confusing me.

目标:我想从文件中读取一个给定的字节第一个字节),并使该字节的ASCII值为int x。因此,例如,如果字节/字符是'a',我想要x为97(=十六进制61)。我有以下读取文件example.txt的第一个字节:

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

#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;
}

问题:如果第一个字节由08,那么我得到一个输出8.但是如果该字节由09表示,那么我得到0.我注意到,我似乎得到以下字节,除非该字节也是09.我不知道如果我的问题只有当字节用ASCII表示为09时。

Problem: If the first byte is represented by 08, then indeed I get an output of 8. But if the byte is represented by 09, then I get 0. I have noticed that I seem to get the following byte unless that byte is also 09. I don't know if my problem is only when the byte is represented in ASCII by 09.

问题:所以我怎么读第一个)字节从文件,并使一个int与该字节的ASCII值?

Question: So how to I read say the first (or third or whatever) byte from a file and make an int with the ASCII value of that byte?

(我在Windows XP)

(I am on Windows XP)

推荐答案

这应该可以解决问题。

 myFile >> noskipws >> b;

这篇关于如何读取字节并在c ++中保存整数字节的ASCII值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆