|< C & C++ Functions 4 | Main | C Formatted I/O 2 >| Site Index | Download |


 

 

 

 

MODULE 5

  THE C FORMATTED  I/O PROGRAMMING 1

------------------------------------------------------------

MODULE 18: THE C++ FORMATTED I/O PROGRAMMING

 

 

 

 

 

 

 

 

My Training Period: xx hours

 

The source code for this Module is available at C Formatted I/O source codes. The lab worksheets for your practice are: main() and printf() scanf()/scanf_s(). Those tutorial also explain the safer version of the stdio.h related functions.

 

The C programming abilities that supposed to be acquired:

 

  • Able to understand and use the C formatted input/output functions library.

  • Able to understand and use predefined/built-in functions and their respective header files.

  • Appreciates other printf() and scanf() family.

 

5.1   Introduction

  • This Module deals with the formatting features of the printf(), scanf(), cin and cout, the most frequently use functions.

  • Here, you will learn how to use the predefined functions provided by the header files (standard or non standard).

  • printf() function input data from the standard input stream.

  • scanf(), output data to the standard output stream.

  • For other functions that use the standard input and standard output are gets(), puts(), getchar() and putchar().  Keep in mind that some of the functions discussed here are non-standard.

  • We have to include header file stdio.h (C) or iostream.h/iostream (C++) in program to call these functions.

5.2    Streams

  • All input and output is performed with stream.

  • Stream is a sequences of characters organized into lines.

  • Each line consists of zero or more characters, and end with the newline character.

  • When program execution begins, these streams are connected to the program automatically.

  • Normally:

  1. The standard input stream is connected to the keyboard.

  2. The standard output stream is connected to the screen/monitor/console.

  3. Redirection of no. 1 and 2 to other devices, a third stream, standard error, connected to the screen.  Error messages are output to the standard error stream.

5.3    Formatting output with printf()

  • For precise output formatting, every printf() call contains a format control string that describes the output format.

  • The format control string consists of:

  1. Conversion specifiers.

  2. Flags.

  3. Field widths.

  4. Precisions.

  5. Literal characters.

  1. Rounding floating-point values to an indicated number of decimal places.

  2. Aligning a column of numbers with decimal points appearing one above the other.

  3. Right-justification and left-justification of outputs.

  4. Inserting literal characters at precise locations in a line of output.

  5. Representing floating-point number in exponential format.

  6. Representing unsigned integers in octal and hexadecimal format.

  7. Displaying all types of data with fixed-size field widths and precisions.

printf (format-control-string, other-arguments);

printf("Using Source IP: %s port: %u\n", argv[1], atoi(argv[2]));

printf("\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f);

5.4  Printing Integers

Conversion specifier

Description

d

Display a signed decimal integer

i

Display a signed decimal integer. (Note: The i and d specifiers are different when used with scanf().)

o

Display an unsigned octal integer.

u

Display an unsigned decimal integer.

x or X

Display an unsigned decimal integer. x causes the digit 0-9 and the letters A-F to be displayed, and x causes the digits 0-9 and a–f to be displayed.

h or l (letter l)

Place before any integer conversion specifier to indicate that a short or long integer is displayed respectively.

 

Table 5.1:  Integer conversion specifiers

// using the integer conversion specifiers

#include <stdio.h>

 

int main()

{

      printf("Various format for integer printing\n");

      printf("-------------------------------------\n");

      printf("%d\n",  455);

      printf("%i\n",  455);  //i same as d in printf()

      printf("%d\n",  +455);

      printf("%d\n",  -455);

      printf("%hd\n",  32000);

      printf("%ld\n",  2000000000L);

      printf("%o\n",  455);

      printf("%u\n",  455);

      printf("%u\n",  -455);

      //-455 is read by %u and converted to the unsigned

      //value 4294966841 by 4 bytes integer

      printf("%x\n",  455);

      printf("%X\n",  455);

     return 0;

}

 

Output:

 

C formatted I/O integer conversion

 

5.5    Printing Floating-point Number

Conversion specifier

Description

e  or  E

Display a floating-point value in exponential notation.

f

Display floating-point values.

g  or  G

Display a floating-point value in either the floating-point form f or the exponential form e ( or E)

l

Place before any floating-point conversion specifier to indicate that a long double floating-point value is displayed.

 

Table 5.2:  Floating-point conversion specifiers

1.502352 x 102

1.502352E+02     by computer

// printing floating-point numbers with floating-point conversion specifiers

#include <stdio.h>

 

void main()

{

      printf("Printing floating-point numbers with\n");

      printf("floating-point conversion specifiers.\n");

      printf("Compare the output with source code\n\n");

      printf("1.  %e\n", 1234567.89);

      printf("2.  %e\n", +1234567.89);

      printf("3.  %e\n", -1234567.89);

      printf("4.  %E\n", 1234567.89);

      printf("5.  %f\n", 1234567.89);

      printf("6.  %g\n", 1234567.89);

      printf("7.  %G\n", 1234567.89);

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

C formatted I/O float number

 

5.6  Printing Strings And Characters

// printing strings and characters

#include <stdio.h>

 

int main()

{

    char character = 'A';

    char string[ ]  =  "This is a string";

    char *stringPtr = "This is also a string";

    printf("---------------------------------\n");

    printf("---Character and String format---\n");

    printf("---------------------------------\n\n");

    printf("%c <--This one is character\n", character);

    printf("\nLateral string\n");

    printf("%s\n", "This is a string");

    printf("\nUsing array name, the pointer to the first array's element\n");

    printf("%s\n", string);

    printf("\nUsing pointer, pointing to the first character of string\n");

    printf("%s\n", stringPtr);

    return 0;

}

 

Output:

 

C formatted I/O string and character

 

5.7     Other Conversion Specifiers

Conversion specifier

Description

p

Display a pointer value (memory address) in an implementation defined manner.

n

Store the number of characters already output in the current printf() statement.  A pointer to an integer is supplied as the corresponding argument.  Nothing is displayed.

%

Display the percent character.

 

Table 5.3:  Other conversion specifiers

 

// using the p, n, and % conversion specifiers

#include <stdio.h>

 

int main()

{

       // pointer variable

       int  *ptr;

       int  x  =  12345, y;

       // assigning address of variable x to variable ptr

       ptr = &x;

       printf("\nUsing the p, n, and %% conversion specifiers.\n");

       printf("Compare the output with the source code\n");

       printf("-----------------------------------------------\n\n");

       printf("The value of pointer ptr is %p\n", ptr);

       printf("The address of variable x is %p\n\n", &x);

       printf("Total characters printed on this line is:%n", &y);

       printf(" %d\n\n", y);

       y = printf("This line has 28 characters\n");

       printf("%d characters were printed\n\n", y);

       printf("Printing a %% in a format control string\n");

       return 0;

}

 

Output:

 

C formatted I/O p n and percent conversion

 

5.8     Printing With Field Widths And Precisions

// printing integers right-justified

#include <stdio.h>

 

int main()

{

     printf("   Printing integers right-justified.\n");

     printf("Compare the output with the source code\n");

     printf("---------------------------------------\n\n");

     printf("%4d\n",  1);

     printf("%4d\n",  12);

     printf("%4d\n",  123);

     printf("%4d\n",  1234);

     printf("%4d\n\n",  12345);

     printf("%4d\n",   -1);

     printf("%4d\n",   -12);

     printf("%4d\n",   -123);

     printf("%4d\n",   -1234);

     printf("%4d\n",   -12345);

     return 0;

}

 

Output:

 

C formatted I/O integer and right justified

 

// using precision while printing integers, floating-point numbers and strings

#include <stdio.h>

 

int main()

{

    int     i = 873;

    float   f =  123.94536;

    chars[ ] = "Happy Birthday";

    printf("Using precision while printing integers,\n");

    printf("  floating-point numbers, and strings.\n");

    printf("Compare the output with the source code\n");

    printf("----------------------------------------\n\n");

    printf("Using precision for integers\n");

    printf("\t%.4d\n\t%.9d\n\n", i, i);

    printf("Using precision for floating-point numbers\n");

    printf("\t%.3f\n\t%.3e\n\t%.3g\n\n", f, f, f);

    printf("Using precision for strings\n");

    printf("\t%.11s\n", s);

    return 0;

 

}

 

Output:

 

C formatted I/O integer and precision

printf("%*.*f", 7, 2, 98.736)

5.9        Using Flags In The printf() Format Control String

Flag

Description

- (minus sign)

Left-justify the output within the specified field

+ (plus sign)

Display a plus sign preceding positive values and a minus sign preceding negative values.

space

Print a space before a positive value not printed with the + flag.

#

Prefix 0 to the output value when used with the octal conversion specifier o.  Prefix 0x or 0X to the output value when used with the hexadecimal conversion specifiers x or X.  Force a decimal points for a floating-point number printed with e, E, f, g, or G that does not contain a fractional part.  (Normally the decimal point is only printed if a digit follows it).  For g and G specifiers, trailing zeros are not eliminated.

0 (zero)

Pad a field with leading zeros.

 

Table 5.4:  Format control string flags

 

// right justifying and left justifying values

#include <stdio.h>

 

int main()

{

        printf("Right justifying and left justifying values.\n");

        printf("  Compare the output with the source code.\n");

        printf("--------------------------------------------\n\n");

        printf("%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23);

        printf("%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23);

        return 0;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

-------------------------------------------------------------------

C formatted I/O right and left justify

// printing numbers with and without the + flag

#include <stdio.h>

 

int main()

{

     printf("Printing numbers with and without the + flag.\n");

     printf("   Compare the output with the source code\n");

     printf("---------------------------------------------\n\n");

     printf("%d\n%d\n", 786, -786);

     printf("%+d\n%+d\n", 786, -786);

     return 0;

}

 

Output:

 

C formatted I/O number without signed

// printing a space before signed values not preceded by + or -

#include <stdio.h>

 

int main()

{

     printf("Printing a space before signed values\n");

     printf("      not preceded by + or -n\n");

     printf("--------------------------------------\n\n");

     printf("% d\n% d\n", 877,  -877);

     return 0;

}

 

Output:

 

C formatted I/O space with signed value

 

// o, x, X, and any floating-point specifier

#include <stdio.h >

 

int main()

{

     int    c  = 1427;

     float  p  =  1427.0;

     printf("o, x, X, and any floating-point specifiers\n");

     printf("Compare the output with the source code\n");

     printf("-----------------------------------------\n\n");

     printf("%#o\n", c);

     printf("%#x\n", c);

     printf("%#X\n", c);

     printf("\n%#g\n", p);

     printf("%#G\n", p);

     return 0;

}

 

Output:

 

C formatted I/O octal hex float

// printing with the 0 (zero) flag fills in leading zeros

#include <stdio.h>

 

int main()

{

       printf("Printing with the 0 (zero) flag fills in leading zeros\n");

       printf("       Compare the output with the source code\n");

       printf("-------------------------------------------------------\n\n");

       printf("%+09d\n", 762);

       printf("%09d", 762);

       printf("\n");

       return 0;

}

 

Output:

 

C formatted I/O print leading 0 flag

 

5.10        Printing Literals And Escape Sequences

Escape sequence

Description

\’

Output the single quote () character.

\"

Output the double quote (") character.

\?

Output the question mark (?) character.

\\

Output the backslash (\) character.

\a

Cause an audible (bell) or visual alert.

\b

Move the cursor back one position on the current line.

\f

Move the cursor to the start of the next logical page.

\n

Move the cursor to the beginning of the next line.

\r

Move the cursor to the beginning of the current line.

\t

Move the cursor to the next horizontal tab position.

\v

Move the cursor to the next vertical tab position.

 

Table 5.5: Escape sequences

Function

Description & Prototype

printf()

Prints output on the standard output stream stdout.  Include stdio.h.

 

int printf(const char *restrict format, ...);

fprintf()

Prints output on the named output stream.  Include stdio.h.

 

int fprintf(FILE *restrict stream, const char *restrict format, ...);

sprintf()

Prints output followed by the null byte, '\0', in consecutive bytes starting at *s; it is the user's responsibility to ensure that enough space is available.  Include stdio.h.

 

int sprintf(char *restrict s, const char *restrict format, ...);

snprintf()

Prints into a string with length checking.  Equivalent to sprintf(), with the addition of the n argument which states the size of the buffer referred to by s. If n is zero, nothing shall be written and s may be a null pointer. Otherwise, output bytes beyond the n-1st shall be discarded instead of being written to the array, and a null byte is written at the end of the bytes actually written into the array.  Include stdio.h.

 

int snprintf(char *restrict s, size_t n, const char *restrict format, ...);

vfprintf()

Print to a FILE stream from a va_arg structure.  Equivalent to printf(), except that instead of being called with a variable number of arguments, they are called with an argument list as defined by stdarg.h.  Include stdarg.h and stdio.h.

 

int vfprintf(FILE *restrict stream, const char *restrict format, va_list ap);

vprintf()

Prints to ‘stdout’ from a va_arg structure.  Equivalent to fprintf() respectively, except that instead of being called with a variable number of arguments, they are called with an argument list as defined by stdarg.h.  Include stdarg.h and stdio.h.

 

int vprintf(const char *restrict format, va_list ap);

vsprintf()

Prints to a string from a va_arg structure.  Equivalent to sprintf() respectively, except that instead of being called with a variable number of arguments, they are called with an argument list as defined by stdarg.h.  Include stdarg.h and stdio.h.

 

int vsprintf(char *restrict s, const char *restrict format, va_list ap);

vsnprintf()

Prints to a string with length checking from a va_arg structure.  Equivalent to snprintf(), except that instead of being called with a variable number of arguments, they are called with an argument list as defined by stdarg.h.  Include stdarg.h and stdio.h.

 

int vsnprintf(char *restrict s, size_t n, const char *restrict format, va_list ap);

 

Table 5.6:  printf() family

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C and C++ reading and digging:

 

  1. Check the best selling C/C++ books at Amazon.com.
  1. The formatted I/O for wide character/Unicode is discussed Locale, Unicode & Wide Characters and the example of the implementation (Microsoft C) is presented Win32 Users and Groups Manipulations.

 

 

 

 

 

|< C & C++ Functions 4 | Main | C Formatted I/O 2 >| Site Index | Download |


C Formatted Input/Output:  Part 1 | Part 2 |