How to convert char to my typedef

I have the following typedef:

typedef unsigned char myType;

Now, I'm collecting characters from a file one at a time like this:

1
2
3
4
5
6
7
	
while(!sin.eof()){
    char * oneChar;
    oneChar  = new char [1]; // not sure what 1 means here, but it's been working
    sin.read(oneChar,1);
    cout.write(oneChar,1); // Correct char			
}


I get the right char from my file but now I want to insert that char into my array of type myType. How can I convert the char into a myType so that I can place it into my array??
Last edited on
I'd like to make one remark on your showed code
You should delete memory allocated in the loop. Otherwise you have a memory leak. So it would be correct to write

1
2
3
4
5
6
7
while(!sin.eof()){
    char * oneChar;
    oneChar  = new char [1]; // not sure what 1 means here, but it's been working
    sin.read(oneChar,1);
    cout.write(oneChar,1); // Correct char
    delete oneChar;			
}


And it would be more better if you did not allocate memory. That is if the code looks like

1
2
3
4
5
while(!sin.eof()){
    char oneChar;
    sin.read(oneChar,1);
    cout.write(oneChar,1); // Correct char			
}


As for your question you can define your array as

myType s[N];

where N - some constant expression.

and then you can assign values to array's elements.

s[i] = static_cast<myType>( oneChar );
operator>> works with unsigned chars:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream>
#include <iostream>

int main()
{
    typedef unsigned char myType;

    std::ifstream f("test.bin", std::ios::binary);
    f >> std::noskipws;
    myType c;
    while(f >> c)
        std::cout << c;
}


but if you need to use read, then it's perfectly fine to reintrepret:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <fstream>
#include <iostream>

int main()
{
    typedef unsigned char myType;

    std::ifstream f("test.bin", std::ios::binary);
    f >> std::noskipws;
    myType c;
    while(f.read(reinterpret_cast<char*>(&c), sizeof c))
        std::cout << c;
}
Topic archived. No new replies allowed.