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);
cout.setf(ios_base::showbase);

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

cout.unsetf(ios_base::showbase);
cout.unsetf(ios_base::hex);

ifs.close();
}

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());

cin.unsetf(ios_base::hex);

ifs.close();
}


This does not work at all.

Any thoughts? Thanks!

Comments

  • [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;
    cin.ignore();
    return 0;
    }
    [/code]

  • 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!

Categories