Input and output streams for C languages

Source: Internet
Author: User
Tags sprintf stdin

1. Standard input and output

The standard input and output are mainly composed of two parts: buffer and Operation method. A buffer can actually be seen as an array of strings in memory, and the operation method mainly refers to the methods of manipulating buffers such as printf, scanf, puts, Gets,getcha, Putcahr, and so on. In object-oriented programming languages such as C + + and Java, the buffers and methods of manipulating buffers are encapsulated into a class of objects, called streams.

The most important feature of the buffer is the one-time data, that is, the data is removed from the buffer by printf, scanf is used, or consumed. The buffer can be likened to a pipeline, the data in the buffer is likened to water flow, printf, scanf and other methods likened to switch, when the switch is turned on, the water will slowly pass, and the flow out of the water will not be back.

Due to the different systems, the hardware underlying implementation of the input and output may not be the same, the C language requires the system to provide two pointers per program, the two pointers to two structures, respectively, the two structures represent the keyboard and the screen in memory abstract representation (the address value of the buffer is recorded in the structure), The pointers to these two structures are named stdin and stdout. These two pointers are the so-called standard input and standard output.

It should always be remembered that the ASCII values of the characters are stored in the standard input and output buffers. For example, if you want to enter 123 from the keyboard to a variable, then store in the buffer is three bytes, respectively, the ASCII value of the character ' 1 ', the ASCII value of the character ' 2 ', the ASCII value of the character ' 3 ', and then convert this three ASCII value sequence to a value to this variable. Similarly, from the screen output "123", the computer does not think it output is a numeric value, the computer is actually only depicts a ' 1 ' ASCII value corresponding to the graphics, ' 2 ' ASCII value corresponding to the graph, ' 3 ' ASCII code value corresponding to the graph. 2. GetChar, Putchar

The main function of Putchar is to write a character to the output buffer.

The main function of GetChar is to read one character to the input buffer. If the end of the file is encountered, return-1

GetChar Source Code

int getchar (void) {staticchar buf[bufsiz];  Staticchar* bb = buf; Static int n = 0; if (n = = 0) {n = read (0, buf, bufsiz); bb = buf;} return Char) *bb++: EOF;

OEF is a macro that represents-1. The return value of GetChar is int, and for a file-1 represents the end of the file. we can use it on the keyboard. Ctrl + Z to achieve a similar effect .

As can be seen from the source code of GetChar, if the character array buf is found to be empty (n==0), call the Read method to read the data from the keyboard (this method causes blocking) and point the pointer to the first address of the array. If the buffer has characters that are not read (n > 0), read it while n-1, and the pointer (BB) moves backwards one bit. When the buffer is empty (n==0) and the Read function fails reading (read to the end of the file), the EOF is returned.

From the source code of SCANF, you can see that GetChar can read any character, including whitespace characters (whitespace, line breaks, tabs, etc.). 3. Gets, puts

The puts function writes a string to the output buffer, and then outputs a newline character ' \ n 'after the string output is finished.

Gets is used to read characters from the input stream's buffer to the specified array. All leading whitespace characters are ignored during the read, and the first character read is non-whitespace until a newline characters is encountered, the end of the newline character (' \ n ') is read from the buffer by the GET function, stored in the array, and replaced '/'.

Get Source code , only need to see the for loop this part of the code, Flockfile (stdin) for the input buffer locking pair; Funlockfile (stdin) indicates that the input buffer is unlocked.

Char* Gets (Char*BUF) {intCChar*s;Static intwarned;Static Const CharW[] = "Warning:this program uses gets (), which is unsafe.\n"; Flockfile (stdin); ORIENT (stdin,-1);if(!warned) {(void) _write (Stderr_fileno, W, sizeof (W)-1); warned = 1;} for(s = buf; (c = __sgetc (stdin))! = ' \ n ';)if(c = = EOF)if(s = = buf) {funlockfile (stdin);return(NULL);}Else Break;Else*s++ = c;*s = 0; Funlockfile (stdin);return(BUF);}

As you can see from the source code, if you read ' \ n ' then stop and replace ' 4 '. Use of printf

Defines the function int printf (const char * format,...);

The function Description printf () Transforms and formats the data according to the parameter format string, and then writes out the result to the standard output device until the end of the string ('% ') occurs.

The parameter format string can contain the following three character types:

(1) General text, accompanied by direct output.

(2) escape characters, such as \ t, \ n, and so on.

(3) format conversion character, format converted to a percent sign (%) and its subsequent format characters. In general, each% symbol must be followed by a printf argument (the% character will be output only when the percent conversion character appears)

Format conversion character detailed "%[symbol [width] [. precision] Type"

[ Width]: Indicates the minimum number of characters for the output

[ symbol]: "-" means alignment

(1)%-8, left-aligned, when the display character is less than 8, right fill space

(2)%08, right-aligned, when the display character is less than 8, left to fill 0

[. accuracy] Number of digits after the decimal point for floating-point numbers

The number of digits after the decimal point is greater than the display precision, only the [. Precision] Number of small tree bits (rounded), or 0 if the number of digits after the decimal point is less than the display precision.

%.5 5 digits after decimal point

type :

(1)%d: Used to display decimal signed number, Char,short,int,long long

(2)%u: Used to display decimal unsigned number, unsinged short,unsigned int,

unsigned long long

(3)%x: Used to display hexadecimal integers, all signed and unsigned integral types

(4)%f: Used to display decimal floating-point numbers, float,double

(5)%c: Display character

(6)%s: Display string

printf ("%s", XXX) with the puts (XXX) difference: The puts function automatically adds line breaks, while printf ("%s",......) No. 5. Use of scanf

Defines the function int scanf (const char * format,...);

The function Description scanf () Converts the input data to the parameter format string and formats the data. The general form of the SCANF () format conversion is as follows:

"%[width [data bytes] input type"

[Width]: The maximum number of characters entered

[Data type]:

H represents two bytes, short

L represents eight bytes, for long long and double

Nothing represents four bytes

[Data type] input type

(1)%d:int

(2)%f:float

(3)%lf:double

(4)%hd:short

scanf ("%c", &x) is equivalent to x = GetChar ()

Although the return value of GetChar is of type int, it does not affect the use of the

(5)%s: string

When reading a string with scanf, the leading white space character is ignored, the whitespace character is encountered again to end the input, and the space character that is encountered again is left in the buffer, and the end sign of the string array is automatically added to '.

#include <stdio.h>void main (intChar* argv[]) {char a[20];  int ch;scanf_s ("%s", a,20);p rintf ("%s\n", a);  while (ch = getchar ())! = EOF) {Putchar (ch);}}

We input I love you (Ctrl + Z)

scanf_s reads the character I after the end (after I is a space), through the GetChar function the first read character is a space, GetChar will always read the buffer until the buffer is empty. 6. Fgets, fputs, fscanf, fprintf, Fgetchar, Fputchar

The above method is only a parameter file * stream, indicating that the input is the stream specified by the file as input or output

Char* fgets (char* _buf, int _maxcount, FILE* _file);

int fputs (const Char * _str,FILE* _file);

int fprintf (FILE* _file, const Char * _format, ...);

int fscanf (FILE* _file, const Char * _format, ...);

int fgetc (FILE* _file);

int FPUTC (int _ch, FILE* _file); 7. Other related functions

int sprintf (char *_dest, const char * format,...);

The function description sprintf is similar to the printf function, where printf writes the result to the standard output stream, and sprintf writes the result to the string array _dest. The return value return value returns the parameter str string length, and the failure returns 1.

#include <stdio.h>void Main () {char* A = "This isstring a!"; Char buf[80];sprintf_s (buf, "begin%s end\n", a);p rintf ("%s", buf);}

int sscanf_s (const Char * _src, const Char * _format, ...);

The SSCANF function is similar to scanf, except that scanf reads the data from the input stream, and sscanf reads the data from the string array _src

#include <stdio.h>void main (intChar* args[]) {int i;  Double n; char str[20] = "123 3.1415"; sscanf_s (str, "%d%lf", &i, &n);p rintf ("%d\n%f\n ", I, n);}

Set stream buffering

int fflush (file* stream);

void setbuf (file* stream, Char* buf);

int setvbuf (file* stream, Char* buf, int mode);

Data is always written (or read) into the stream, and when the buffer is full, it works more efficiently when it is written to the device (or gets read into the program). But sometimes we may need a faster corresponding speed, we can call the Fflush method to flush the buffer, note that this flushing means not to delete the contents of the buffer, but rather to write the contents of the buffer that is not full to the device (or read into the program).

The position and size of the buffer can be set by the parameter buf itself (the size is determined by the size of the BUF array) in SETBUF.

The third parameter in the SETVBUF mode determines the buffer type of the buffers. It is evaluated by three kinds of values

_IOFBU: Full Full buffer type

_IOLBU: Line Full buffer type

_ionbu: No buffer type

Input and output streams for C languages

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.