Search code examples
c++stringio

What's the C++ equivalent of %x.ys format specifier from C?


How can I replace printf() with cout? My Code In C++:

    #include<iostream>
    #include<cstdio>
    using namespace std;
    int main ()
    {
        char st[15]="United Kingdom";
        printf("%5s\n",st);
        printf("%15.6s\n",st);
        printf("%-15.6s\n",st);
        printf("%.3s\n",st); // prints "Uni"
        return 0;
    }

The Code Prints:

United Kingdom

       United

United

Uni

How can I manipulate like this in C++?


Solution

  • 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