C++

C++ String Formatting

String formatting means putting certain characters for a string in particular positions and a particular order. This also involves the insertion of whitespace characters in certain positions. C++20 is the latest version of C++. It has a format library, and g++, which is one of the most popular C++ compilers, implements it. However, the printf() variadic function, incorporated into the C++ language from the C language, is similar to the purpose of the format library. A variadic function is a function that can take a variable number of arguments, at different times.

A string can be formatted, sending it out to the console or sending it to a file. This tutorial explains the formatting of a string, using the printf() function, sending it out to the terminal (console). In C++, the printf() function can be used, through the inclusion of the <cstdio> library.

Article Content

– Arithmetic Types

– Variadic Nature of printf

– String Type

– Whitespace

– Conclusion

Arithmetic Types

Arithmetic types are integer and floating types. Consider the following program:

    #include <cstdio>

    using namespace std;
 
    int main()
    {
        printf("some text\n");
   
        return 0;
    }

The output is:

some text

The first argument to the printf() function is a string literal. The newline character, “\n” in the string literal, forces anything to be printed next to be printed on the next line, even if that thing is within the double-quotes. The “\n” is also a whitespace character.

With the inclusion of <cstdio>, “#include <iostream>” is not really necessary.

Integer

Consider the following printf() statements:

printf("Number is: %i\n", 52);

printf("Number is: %d\n", 52);

The output is:

Number is: 52

Number is: 52

The %i or %d is an example of a format specifier. %i within the first argument of the printf function, which is a string literal, means replace itself with the integer value that is the next argument of the printf function. %d is a synonym to %i. The “\n” will always play its role in sending what is to be printed next to the next line at the terminal. A specifier such as %i, typed next to \n, poses no conflict of interest. The second argument to the printf() function can be a variable.

By replacing itself with the next argument value of the printf function, the specifier is said to be expanded to the corresponding value. Note: %i is for an integer, while %f is for a float number.

Now, if one zero is inserted between % and the actual specifier, i, i.e., %0i for 1 zero, then 52 will be outputted as 52. If it is %02i, for 2 zeros, 52 will still be outputted as 52. If it is %03i, for 3 zeros, 52 will be outputted as 052. One zero has been added, in the third position, counting from the right end of the number. If it is %04i, for 4 zeros, 52 will be outputted as, 0052. Two zeros have been added, in the fourth position, counting from the right end of the number.

In this context, zero is called a flag. The following program illustrates this:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("Number is: %0i\n", 52);
        printf("Number is: %02i\n", 52);
        printf("Number is: %03i\n", 52);
        printf("Number is: %04i\n", 52);
   
        return 0;
    }

The output is:

Number is: 52

Number is: 52

Number is: 052

Number is: 0052

Zero in this context is called a flag. Another possible flag is the space. The following program illustrates this for the space:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("Number is: %i\n", 52);
        printf("Number is: %2i\n", 52);
        printf("Number is: %3i\n", 52);
        printf("Number is: %4i\n", 52);
   
        return 0;
    }

The output is:

Number is: 52

Number is: 52

Number is: 52

Number is: 52

Note that with the space flag, no character is used in the format specifier. A flag is added in front of the number to make up the number of positions requested for the presentation field, counting from the right. If the number of positions is less than or equal to the number of digits, no flag is added.

Field Width

A field is the number of characters that can be displayed for that number. A field width is the maximum number of characters that the programmer hopes to get. The field width number is inserted just after the flag (rightward) in the format specifier. It is the same as the previous number. If the number of characters to be displayed is naturally greater than the field width, the printf() function will allow it. The following program illustrates this:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("Number is: %03i\n", 1);
        printf("Number is: %03i\n", 12);
        printf("Number is: %03i\n", 123);
        printf("Number is: %03i\n", 1234);
        printf("Number is: %03i\n", 12345);
   
        return 0;
    }

The output is:

Number is: 001

Number is: 012

Number is: 123

Number is: 1234

Number is: 12345

Float

A floating point number is a number with the integer part and a decimal part. Note, the integer part is not represented as an integer, internally. The actual specifier for the float is ”f”. The following program illustrates this:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("Number is: %f\n", 2.53);
   
        return 0;
    }

The output for the author’s computer is:

Number is: 2.530000

This number naturally has 2 decimal places. Unfortunately, 4 decimal places of 4 zeros were appended. The truth is, the author’s computer rounds the number of decimal places to 6. It will append zeros to make up for 6 decimal places if the natural number of decimal places is less. The number of decimal places can be decided by the programmer. It can be less than or equal to 6, or it can be greater than 6.

This intention needs another code component, called the precision component, for the format specifier. It consists of the dot and a number for the number of decimal places wanted. The following program illustrates this:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("Number is: %f\n", 2.53);
        printf("Number is: %.1f\n", 2.53);
        printf("Number is: %.2f\n", 2.53);
        printf("Number is: %.3f\n", 2.53);
        printf("Number is: %.8f\n", 2.53);
   
        return 0;
    }

The output is:

Number is: 2.530000

Number is: 2.5

Number is: 2.53

Number is: 2.530

Number is: 2.53000000

Note that “.0” is not in any of the specifiers.

Variadic Nature of printf

The first argument of the printf() function is a string literal. Format specifiers can be interspersed within the string literal. The first format specifier from the left, in the string literal, corresponds to the second argument of the printf() function. The second format specifier from the left, in the string literal, corresponds to the third argument of the printf() function. The third format specifier corresponds to the fourth argument of the printf() function and so on. The following program illustrates this for the int and float types:

    #include <cstdio>

    using namespace std;

    int main()
    {
        int it = 52;
        float ft = 2.53;

        printf("Numbers are, %03i and %03i and %.3f\n", 27, it, ft);
   
        return 0;
    }

The output is:

Numbers are 027 and 052 and 2.530

String Type

The basic string format specifier is %s. The following program shows its use:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("%s", "I love you.\n");
   
        return 0;
    }

The output is:

I love you.

The ‘\n’ character is to send whatever is printed next to the next line. All the first argument here has %s as content.

The different possible ways of using numbers, with the string format specifier, are as follows:

%nums

%.nums

%-nums

%.num1-num2s

%-num1.num2s

%nums

There are 11 characters in the string, “I love you.” The dot is a character. If num is less than 11, the output string will not be truncated. If it is greater than 11, extra spaces will be padded on the left to make the total number of characters in the field the number given. The following code illustrates this:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("%7s", "I love you.\n");
        printf("%16s", "I love you.\n");
   
        return 0;
    }

The output is:

I love you.

I love you.

%.nums

Here, there is a dot in front of the number. The dot here means print the number of characters of the given number, beginning from the first character. This means, if num is less than the total number of characters, truncate the balance on the right. If num is more, add spaces on the right to make up for the given number. The following program illustrates this:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("%.7s", "I love you.\n");
        printf("%.16s", "I love you.\n");
   
        return 0;
    }

The output is:

I love I love you.

This output needs further explanation. In the string “I love you.\n”, there are 12 characters. “\n” is a character. The first 7 characters are “I love ”. The program’s first printf() function prints this: “I love ”, truncating the rest of the string literal, including “\n”. Since “\n” of the first “I love you.\n” has been taken off, whatever has to be printed next, is printed on this line. The second printf() function prints its 11 characters. The twelfth character, which is “\n”, causes the cursor to go to the next line. Then, 4 more spaces should be printed next.

%-nums

Here, there is a hyphen in front of the number. The hyphen means, print the number of characters of the given number, beginning from the first character. Plus, do not truncate if num is less than the total number of characters. Simply add more spaces on the right to make up for the given number. The following program illustrates this:

    #include <cstdio>

    using namespace std;

    int main()
    {
        printf("%-7s", "I love you.\n");
        printf("%-16s", "I love you.\n");
   
        return 0;
    }

The output is:

I love you.

I love you.

cursor

The cursor appears after 4 extra spaces in the third line.

%.num1-num2s, %-num1.num2s

The interpretation of these two items is left as an exercise for the reader.

Whitespace

The “\n” is an example of a whitespace character. Whitespace characters are escape sequences. They are not printed. They just have their individual effects. For example, “\n” causes the cursor to go to the following line. In the previous code samples, this “\n” has been employed inside the first argument of the printf() function, a string literal. It can still be employed as a variable, as the following program shows:

    #include <cstdio>

    using namespace std;

    int main()
    {
        char vr = '\n';
        printf("first line%csecond line", vr);
   
        return 0;
    }

The output is:

first line

second lineCURSOR

The following are whitespaces and their meanings:

\n: add a newline

\t: horizontal tab

\v: vertical tab

\f: form feed

\040: single space by pressing the space bar key

\r: carriage return

Conclusion

String formatting means putting certain characters for a string, in particular positions and particular order. This also involves the insertion of whitespace characters in certain positions. C++20 is the latest version of C++. It has a format library. However, most C++ compilers have not yet implemented this library. Note, the printf() variadic function, incorporated into the C++ language from the C language, is similar to the purpose of the format library. The first argument to this function is a string literal. The format specifiers are interspersed within. The rest of the arguments to the printf() function correspond to these specifiers in order.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.