Usage Summary C language fgets () function

After c ++ 11 removed from the gets () function, instead of using fgets (), the use of different, detailed here under fgets () how to use.

char * fgets (char * __ restrict __s, int __n, FILE * __ restrict __stream)
The first argument is a data storage array, the second parameter is the maximum length, the third parameter is the input source, we read from the keyboard, the parameters as stdin.


#include <stdio.h>
#include <cstring>

char A[20];
int main() {
    fgets(A , 20, stdin);
    int lengthA = strlen(A)-1;
    printf("lenA:%d\n",lengthA);
    printf("start: %c\n",A[0]);
    printf("end: %c",A[lengthA-1]);
    return 0;
}

Here Insert Picture Description

See fgets () read contains string length trailing '\ 0', to be noted that while traversing an array subscript bounds. strlen (A) -1 is the actual length of the string.

If you want to specify the location to store the string it

You can be specified to start the first parameter storage location


#include <stdio.h>
#include <cstring>

char A[20];
int main() {
    fgets(A+1 , 20, stdin);
    int lengthA = strlen(A+1)-1;
    printf("lenA:%d\n",lengthA);
    printf("start: %c\n",A[1]);
    printf("end: %c",A[lengthA]);
    return 0;
}

Here Insert Picture Description

We insert 1 from the position of the subscript a string asd 3, in which case A [0] position a null string length should be calculated starting from the corresponding A + 1, as strlen (A + 1), or It is wrong.
We use strlen (A) test as follows:
Here Insert Picture Description

Use fgets (), also using the corresponding fputs () output.
fputs (const char * __ restrict __s , FILE * __ restrict __stream)
The first argument is the array output, the second parameter is output. We use the stdout output to the screen

Published 51 original articles · won praise 1 · views 6047

Guess you like

Origin blog.csdn.net/qq_39827677/article/details/104534019