c Programming Language by K&R Input and Output

1. Standard Input and Output

1. Simple InputOutput Mechanism

  • Read one character at a time from standard input: int getchar(void)
  • Send the character c to standard output: int putchar(int)

2. Input redirection

  • If the getchar function is used in the program prog, then prog < infile causes the program prog to read characters from the input file infile.
  • This input switch is also invisible if the input is piped from another program. For example, the command otherprog | prog redirects the standard output of the program otherprog to the standard input of the program prog via a pipeline.

3. Output redirection

  • If the putchar function is used in the program prog, then prog > file redirects the standard output of the program prog to the file.
  • If the system supports piping, prog | anotherprog redirects the program's standard output through the piping to the program's anotherprog standard input.

2. Formatted Output - Pritf Function

1. Complete Form

int printf(char* format, arg1, arg2, arg3,....);
  • '-', negative sign. Specifies that the converted parameters are output as left-aligned.
  • Number (before decimal point). Specify the minimum field width. If the character length is insufficient, the space is filled.
  • Decimal point. Separate the field width from the precision.
  • Number (after decimal point). Specifies the maximum number of characters to print in a string, the number of digits after the decimal point of a floating point number, and the number of digits to reshape the minimum output.

2. Basic conversion instructions

character Output Form
d,i int, decimal number
o int, unsigned octal number
x int, unsigned hexadecimal number
u int, unsigned decimal number
c int type, single character
s char* type until'\0'or the number of characters specified by precision is printed
f double type, decimal decimal, [-]m.d d d d d d, d number specified by precision
e,E double type, [-]m.d d d d d E [+-] xxx, d number specified by precision
g,G double type, if exponent is less than-4 or greater than or equal to precision, use%e,%E output, otherwise use%f output
p void*type; Pointer
int main() {
    double a = 100;
    printf("%e\n", a);
    return 0;
}

The output is:

1.000000e+002

3. Precision control of string output

#include <stdio.h>
#include <stdlib.h>

int main(void) {
	char* s = "hello, world"; //12 char
	printf("-%s-\n",s); //Use-to indicate width boundaries
	printf("-%10s-\n",s); 
	printf("-%.10s-\n",s);
	printf("-%-10s-\n",s); // -Left Alignment
	printf("-%15s-\n",s);
	printf("-%-15s-\n",s);
	printf("-%15.10s-\n",s);
	printf("-%-15.10s-\n",s);

	int max = 5;
	printf("-%.*s-\n", max, s); //Width or precision can be represented by an asterisk * whose value can be calculated by converting to the next parameter, which must be of type int.

	return 0;
}

output

-hello, world-
-hello, world-
-hello, wor-
-hello, world-
-   hello, world-
-hello, world   -
-     hello, wor-
-hello, wor     -
-hello-

4. sprintf function

int sprintf(char* string, char* format, arg1, arg2, ...);

Format the sequence parameters arg1,arg2,... In format. Store the output in a string. String needs space large enough to accommodate results.

3. Variable length parameter table

1.Several va_ Macro Definition

  • Va_ List: va_ List ap; Used to declare a variable AP (arg pointer), referencing each parameter in turn.
  • va_start: va_start(ap, namedArg); Initialize AP as a pointer to the first unnamed parameter. Before using ap, the macro must be called in turn. The parameter table must contain at least one parameter, va_start takes the last named parameter as the starting point.
  • va_arg:va_arg(ap, int) The function returns one parameter and points AP to the next parameter. va_arg uses a type name to determine the type of object returned and the step by which the pointer moves.
  • va_end:va_end(ap); Finally, you need to call va_before the function returns End to do some necessary cleanup.

2. Implement a miniprintf

void minprintf(char* fmt, ...){
    va_list ap;
    char* p, *sval;
    int ival;
    double dval;
    va_start(ap, fmt);

    for(p = fmt; *p; p++){
        if(*p != '%'){
            putchar(*p);
            continue;
        }
        switch(*++p){
            case 'd':
                ival = va_arg(ap, int);
                printf("%d", ival);
                break;
            case 'f':
                dval = va_arg(ap, double );
                printf("%f", dval);
                break;
            case 's':
                for(sval = va_arg(ap, char*); *sval; sval++){
                    putchar(*sval);
                }
                break;
            default:
                putchar(*p);
                break;
        }
    }
    va_end(ap);
}

3. Implement a variable parameter accumulation function

long long int sum(int num,...) Where num is the number of accumulative integers.

#include <stdio.h>
#include <stdarg.h>

long long int sum(int num, ...){
    long long int result = 0;
    va_list ap;
    va_start(ap, num);
    while(num--){
        result += va_arg(ap, int);
    }
    va_end(ap);
    return result;
}
int main() {
    printf("%lld", sum(3,2,3,4));
    return 0;
}

The output is:

9

Keywords: C

Added by rfigley on Wed, 12 Jan 2022 19:19:59 +0200