打印字符数组时显示的随机字符

Cha*_*Ray 0 c++

这是我的问题.我正在以二进制模式读取文件,将字节附加到int数组,然后打印值.我的问题是,当我结果我的结果时,随机字符被附加在流中.

comp.txt:

this text is a testt1
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

注意事项:

  • temp只有4个字节,但是打印了5个字节

yan*_*yan 6

在temp中读取时,用数据覆盖所有4个字符,不带NULL终止符.cout.operator <<(char*)需要一个以null结尾的字符串,因此它会打印尽可能多的字符,直到它到达null终止符.使temp为5个字符长,所有'\ 0',但保持读取的字节数为4将缓解该问题.