Hello,

I'm having trouble with something..

I have a vector of doubles and I need to convert the vector to an unsigned char so then I can write the contents to a text file. I can do this when reading the data from a text file, just not from a vector.

void writeToImage(const vector<double>& matrix)
{
    vector<unsigned char> image(matrix.size());

    image.push_back(reinterpret_cast<unsigned char>(matrix[0]));
}

This was just a small example that I've been playing around with. But also have tried this:

void writeToImage(const vector<double>& matrix)
{

    vector<unsigned char> image(matrix.size());

    for(int i=0; (i < 512*512); i++)
    {
        image[i]=(unsigned char)matrix[i];
    }

    cout << image[0];

 }

Could anyone help me please?

If you convert the matrix of double into a matrix of chars, you might lose some data since char cannot hold the same range of data as double can. You can copy like so std::vetor<unsigned char> pixels(matrix.begin(),matrix.end()). What problem are you having exactly?

Hello,

Thanks for the reply.. So basically, if I have: 0 in the vector, after the conversion the value would then be: (something like) 0.0000000e+000 which can then be written back to the file..

I know that I need to convert it back to an unsigned char, the problem is when trying to populate it, no values are entered:

void writePNG(vector<double>&theMatrix)
{
    vector<unsigned char> pixels(theMatrix.size());

    for(int i=0; (i < 512*512); i++)
    {
        pixels.push_back(theMatrix[i]);
    }

    cout << pixels[1];
}

Even when I try to use "reinterpret_cast<unsigned char>" it errors out.

I have a vector of doubles and I need to [...] write the contents to a text file.

What's wrong with simply opening the file in text mode, iterating through your vector and outputing each double?

main.cpp

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

using namespace std;

int main()
{
    vector<double> vec;

    vec.push_back(1.2345678935);
    vec.push_back(2.1957203851);
    vec.push_back(3.2230343852);
    vec.push_back(0.5534203832);

    ofstream fout("out.txt");

    fout.setf(ios::fixed);
    fout.precision(10);

    for (size_t i = 0; i < vec.size(); ++i)
        fout << vec[i] << '\n';

    fout.close();
}

out.txt

1.2345678935
2.1957203851
3.2230343852
0.5534203832
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.