Zufällige Zeichen angezeigt, beim drucken array von Zeichen

Dies ist mein problem. Ich lese eine Datei im binary-Modus anfügen von bytes zu einem int-array und Druck-die Werte nach. Mein problem ist, wenn ich cout meine Ergebnisse, zufällige Zeichen sind befestigt, in den Strom.

comp.txt:

this text is a testt1

main.cpp:

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


using namespace std;

void read(ifstream& stream, unsigned int buf[], int size)
{
    for(int i = 0; i < size; ++i)
    {
        unsigned char temp[4] = {'\0', '\0', '\0', '\0'};
        stream.read((char*)temp, 4);
        cout << "Temp: " << temp << '\n';
        buf[i] = *((int*)temp);     
        cout << "Read: " << buf[i] << endl;
        memset(temp, '\0', 4);
    }
}

int main()
{

    //open file
    ifstream f;
    f.open("comp.txt", ios::binary);
    cout << "File opened. " << endl;

    //get size
    f.seekg(0, ios::end);
    int l = f.tellg();
    int length = (l / 4) + 1;
    f.seekg(0, ios::beg);
    cout << "Size found: L: " << l << " Length: " << length << endl;

    //allocate byte arrays
    unsigned int* buf = new unsigned int[length];
    memset(buf, '\0', 4*length);
    //unsigned short* key = new unsigned short[length];
    cout << "Preparing to read..." << endl;

    //read byte into short
    cout << "Reading..." << endl;
    read(f, buf, length);
    f.close();
    delete[] buf;
    cin.ignore(1000, 10);
    return 0;
}

Ausgabe:

C:\Users\daminkz\Desktop>encrypt
File opened.
Size found: L: 21 Length: 6
Preparing to read...
Reading...
Temp: this
Read: 1936287860
Temp:  tex
Read: 2019914784
Temp: t is
Read: 1936269428
Temp:  a t
Read: 1948279072
Temp: estt
Read: 1953788773
Temp: 1
Read: 49

Dinge zu beachten:

  • temp ist nur 4 bytes, aber 5 bytes gedruckt
  • Ein Rat: verlassen Sie sich nicht auf int 32 bit breit. #include <stdint.h> und verwenden uint32_t.
InformationsquelleAutor Charles Ray | 2011-01-14
Schreibe einen Kommentar