Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ofstream.setf() function 1

Status
Not open for further replies.

titanandrews

Programmer
Feb 27, 2003
130
US
Hi,
Either I am doing something wrong or Microsoft C++ compiler is. I took an example from Practial C++ Programming book, page 251. Supposedly the integer 1023 should be printed out in decimal format and then in hex format. But when I run it, there is no difference. I tried printing to file and to stdout and the results are the same. What am I missing here? Many thanks!

Code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
    int myInt = 0x3FF; //1023
    ofstream outFile(&quot;MyOutputFile.txt&quot;,std::ios::out);
    outFile << &quot;Hello&quot; << endl; //Print a string   
    cout << &quot;Hello&quot; << endl ;   //Echo to console

    outFile.setf(std::ios::dec);
    cout.setf(std::ios::dec);
    outFile << myInt << endl; //Print an int in decimal format
    cout << myInt << endl;    //Echo to console

    outFile.setf(std::ios::hex);
    cout.setf(std::ios::hex);    
    outFile << myInt << endl; //Print an int in hex format
    cout << myInt << endl;    //Echo to console
        
    return(0);
}
 
Use setf like this instead:

cout.setf(ios_base::hex, ios_base::basefield );

<MSDN>
ios::setf( IFlags ) should not be used with a flag value of ios::dec, ios::eek:ct, or ios::hex unless you know that none of the base flags are currently set. The formatted input/output functions and operators assume that only one base is set. Instead, use ios_base. For example, setf( ios_base::eek:ct, ios_base::basefield ) clears all base information and sets the base to octal
</MSDN>

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top