I/O with conversions

I have a simple text file that contains some words. I wrote a program that would read in the text and print out the hexidecimal values of each character. It went something like this...

ifstream ifs("words.txt");

if (ifs) {
cout.setf(ios_base::hex, ios_base::basefield);

copy(istreambuf_iterator(ifs), istreambuf_iterator(), ostream_iterator(cout, " "));



This program works fine. So, I thought that doing the reverse, which would be to read from a text file that contained hexidecimal values and print out the character equivalents, would be easy.

I made a file that consists of hexidecimal codes, separated by spaces:

For example:
0x73 0x61 0x76 0x65

And here's the code....

ifstream ifs("hex.txt");

if (ifs) {
// interpret the values from stdin as hex
cin.setf(ios_base::hex, ios_base::basefield);

// read each hex value in and print it out as char
copy(istream_iterator(cin), istream_iterator(), ostream_iterator());



This does not work at all.

Any thoughts? Thanks!


  • [code]
    int main()
    int x;
    string str;
    FILE * fp = fopen("stuff.txt","r");
    while(fscanf(fp,"%X",&x) > 0)
    str += x;
    cout << str.c_str() << endl;
    return 0;

  • Thanks.

    Actually, I was able to figure out the problem. I was setting the flags for cin instead of the file stream (duh). Once I corrected this, my code worked.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!