使用cout的C ++怪异行为?

时间:2017-08-11 19:40:01

标签: c++ for-loop printf cout codepages

行。所以我编写了这个代码,它所做的就是打印16个十六进制值然后打印16个字符,然后为下一行打印换行符。在for循环中,我注意到我必须以某种方式去打印127以上的任何东西,为什么我不知道,这就是我在这里问你的原因。

最重要的是,有没有人有关于使用cout与十六进制的任何指针?因为我不得不导入一个额外的模块,只是为了将cout的宽度设置为2。

这段代码刚刚练习,我想输出看起来像是在十六进制编辑器HxD中。我想我只能使用一个字符串,而不必在字符串声明中复制两次相同的值。

但是,是的,任何指针或批评请不要拖延。

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

#define SIZE 0x830

using namespace std;

int main(int argc, char * argv[])
{

    int i, j, k;

    ifstream dump(argv[1], ios::binary);

    char* buffer = new char[SIZE];

    if (dump.is_open())
    {
        dump.read(buffer, SIZE);
        dump.close();
    }
    else
    {
        cout << "no success :(\n";
        exit(0);
    }

    std::string my_hex;
    std::string my_char;

    for (int i = 0; i < SIZE; i++)
    {
        my_hex += buffer[i];
        my_char += buffer[i];
    }

    for (int j = 0; j <= 2095; j++)  //j is the position we are in the loop, which means that j also equals current character.
    {

        if ((j % 16 == 0) && (j != 0)) //if j is divisible by 16 and does not equal 0 then enter this if block, otherwise just print my_hex[j]
        {

            for (k = 0; k <= 15; k++) 
            { //handle regular characters

                if ((my_char[(j + k) - 16] >= 0) && (my_char[(j + k) - 16] <= 31) || (my_char[(j + k)] == 255))
                { // this checks if the value is lower than 31 or equal to 255, either which can have a '.' printed in its place.
                    cout << ".";
                }
                else if ((my_char[(j + k) - 16] >= 32) && (my_char[(j + k) - 16] <= 127))
                { //if value is greater than or equal to 32 or equal to or less than 127 it will print that character, remember to print the correct character. we must go back to the beginning of the string with - 16.
                    cout << my_char[(j + k) - 16];
                }
                else
                {
                    cout << my_char[(j + k) - 16];  //prints everything above 127
                };

            }
            cout << "\n";
        }
        printf("%02x ", (unsigned char) my_hex[j]); //print hexadecimal values of characters
    }
    dump.close();
    return 0;
}

如果您认为自己知道更好的方式,请务必赐教:) *我必须将cmd中的代码页交换为1252(ANSI),以使字符输出与HxD相比看起来正确。

0 个答案:

没有答案