Thread: base conversion in cout (oct, hex)

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    46

    base conversion in cout (oct, hex)

    Why doesn't this code output the number in octal format?

    Code:
    #include <iostream.h>
    #include <iomanip.h>
    
    int main ()
    {	
    	cout << setiosflags(ios::oct) << 15
    	     << endl;
    		
    	return 0;
    }
    The output is 15, but it should be 17.

    using just
    Code:
    cout << oct << 15
    works fine.

    Thanks.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    If more than one basefield flag is set then decimal is used. You need to use resetiosflags() to reset ios::basefield before setting ios::oct:
    Code:
    #include <iomanip>
    #include <iostream>
    
    int main()
    {
      std::cout<< std::resetiosflags(std::ios::basefield)
        << std::setiosflags(std::ios_base::oct) << 15 <<'\n';
    }
    Using the std::oct manipulator is much easier, and it does the right thing, thus saving you the hassle of worrying about unsetting and resetting flags.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary to Hex Conversion
    By elrookie in forum C Programming
    Replies: 8
    Last Post: 06-26-2007, 10:58 AM
  2. Virtual Base Class & Constructor :: C++
    By kuphryn in forum C++ Programming
    Replies: 2
    Last Post: 09-13-2002, 03:14 PM
  3. base conversion algo
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 12-28-2001, 09:28 PM
  4. Base conversion problem!
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 10-08-2001, 07:00 PM
  5. Base Conversion
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 10-07-2001, 10:27 PM