[Solved] In C ,we use %x.ys for string manipulation. What it will be in C++?


The std::setw() I/O manipulator is the direct equivalent of printf()‘s minimum width for strings, and the std::left and std::right I/O manipulators are the direct equivalent for justification within the output width. But there is no direct equivilent of printf()‘s precision (max length) for strings, you have to truncate the string data manually.

Try this:

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    char st[15] = "United Kingdom";

    cout << setw(15) << st << '\n'; // prints " United Kingdom"
    cout << setw(5) << st << '\n'; // prints "United Kingdom"
    cout << setw(15) << string(st, 6) << '\n'; // prints "         United"
    cout << left << setw(15) << string(st, 6) << '\n'; // prints "United         "
    cout << setw(15) << string(st, 0) << '\n'; // prints "               "
    cout << string(st, 3) << '\n'; // prints "Uni"
    cout << st << '\n; // prints "United Kingdom"

    return 0;
}

Live demo

solved In C ,we use %x.ys for string manipulation. What it will be in C++?