dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jan 2012
    Location
    USA
    Posts
    91

    [RESOLVED] How to pad a string with trailing zeros using ostringstream

    Hi,

    The code that I have does not work. Could some help -- thanks.

    Code:
    
    #include <iostream>
    #include <iomanip>
    #include <sstream>
    
    int main()
    {
            std::string str3 = "99W8";
            std::ostringstream ss4;
            ss4 << str3 << std::setw(7) << std::setfill('0');
            std::string s4(ss4.str());
            std::cout << s4 << std::endl;
            return 0;
    }

  2. #2
    VictorN's Avatar
    VictorN is online now Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    19,144

    Re: How to pad a string with trailing zeros using ostringstream

    define "does not work"
    Victor Nijegorodov

  3. #3
    Join Date
    Jan 2012
    Location
    USA
    Posts
    91

    Re: How to pad a string with trailing zeros using ostringstream

    the output:
    99W8

    I would like it to be:
    99W8000

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    6,210

    Re: How to pad a string with trailing zeros using ostringstream

    Code:
    ss4 << str3 << std::setw(7 - str3.length()) << std::setfill('0') << "";
    After you set the width, you need to output something.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++17 Compiler: Microsoft VS2017 (15.7.2)

  5. #5
    Join Date
    Jan 2012
    Location
    USA
    Posts
    91

    Re: How to pad a string with trailing zeros using ostringstream

    That's slick, @2kaud, thank you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)