George
George

Reputation: 1

C++ turning a .txt with Hexa characters to a .txt with hexa characters with \x in front

I would like to ask if there is a method in C++ to turning a .txt file with hexa digits for example

0E 1F BA 0E 00 B4 09 CD 21 B8 01 4C CD 21 54 68 69 73 20 70 72

to a new .txt with that looking

\x0E\x1F\xBA\x0E\x00\xB4\x09\xCD\x21\xB8\x01\x4C\xCD\x21\x54\x68\x69\x73\x20\x70\x72"

I searched the answer in google but found nothing and tried a script in C++ but does not work with error message "24 11 \x used with no following hex digits"

#include <iostream>
#include <fstream>
#include<vector>

using namespace std;


int main()
{

string hexaEnter;
ifstream read;
ofstream write;

write.open ("newhexa.txt",std::ios_base::app);

read.open("hexa.txt");

while (!read.eof() )
    {

    read >> hexaEnter;

    write << "\x" + hexaEnter;

    }
write.close();
read.close();

system("pause");
return 1;
}

Upvotes: 0

Views: 50

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385295

write << "\x" + hexaEnter;
//        ^^

Here, C++ sees the beginning of a hex escape sequence, like \x0E or \x1F, but it can't find the actual hex values because you didn't provide any.

That's because what you intended to do was literally write the character \ and the character x, so escape the backslash to make that happen:

write << "\\x" + hexaEnter;
//        ^^^

As an aside, your loop condition is wrong.

Upvotes: 1

Related Questions