[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1253
  • Last Modified:

Left-Justified String formatting in C++

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
0
nicoleheritage
Asked:
nicoleheritage
1 Solution
 
SteHCommented:
add the line
outfile.setf (ios::eft, ios::adjustfield);
before the output
0
 
stefan73Commented:
Hi nicoleheritage,

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

Use "-" to left-justify:

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


Cheers!

Stefan
0
 
itsmeandnobodyelseCommented:
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;
    outfile.close();
    return 1;
   
}

Regards, Alex

0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now