Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


Left-Justified String formatting in C++

Posted on 2004-10-25
Medium Priority
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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 13

Expert Comment

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

Accepted Solution

stefan73 earned 200 total points
ID: 12401437
Hi nicoleheritage,

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

Use "-" to left-justify:

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


LVL 39

Expert Comment

ID: 12401729
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


Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

636 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