Left-Justified String formatting in C++

Posted on 2004-10-25
Last Modified: 2006-11-17
The sprintf command provides a right justified string. Is there anyway I can create a left justified string with trailing spaces instead of preceding spaces followed by the text string. For instance
char outputRecord[112];
sprintf (outputRecord, "%32s","Output Text");
outfile << outputRecord << std::endl;

Current output on executing the above code produces
sssssssssssssssssssssOutput Text where s = space

Expected output on executing the above code
Output Textsssssssssssssssssssss where s = space
Question by:nicoleheritage
    LVL 13

    Expert Comment

    add the line
    outfile.setf (ios::eft, ios::adjustfield);
    before the output
    LVL 12

    Accepted Solution

    Hi nicoleheritage,

    > sprintf (outputRecord, "%32s","Output Text");

    Use "-" to left-justify:

    sprintf (outputRecord, "%-32s","Output Text");


    LVL 39

    Expert Comment

    Or that:

    #include <fstream>
    #include <iomanip>
    using namespace std;

    int main(int argc, char* argv[], char *envp[])
        ofstream outfile("out.txt");
        char outputRecord[112] = "Output Text";
        outfile<< setiosflags(ios_base::left) << setw(32)  << outputRecord << std::endl;
        return 1;

    Regards, Alex


    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
    Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
    The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.
    The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

    875 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now