base conversion in cout (oct, hex)

This is a discussion on base conversion in cout (oct, hex) within the C++ Programming forums, part of the General Programming Boards category; Why doesn't this code output the number in octal format? Code: #include <iostream.h> #include <iomanip.h> int main () { cout ...

  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,796
    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, 08: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21