An overview of

  1. Concatenated string literals, equivalents, string arrays, and Pointers to const
  2. Store multiple different strings: pointer representation and array representation
  3. Gets, fgets, fputs, puts, gets_s, putchar, getchar, scanf, printf comparison
  4. NULL characters, whitespace, EOF, NULL pointer
  5. String functions: strlen, strcat, strncat, STRCMP, STRNCMP, strcpy, strncpy, sprintf, STRCHR, STRRCHR, STRPBRK, STRSTR
  6. Ctype. h Character-specific functions
  7. Command line argument, if the argument is an integer

The sample

  1. Concatenated string literals, equivalents, string arrays, and Pointers to const
#include<stdio.h>
int main(void){
    // Concatenated string literals (constants), "" between the space, if broken, pay attention to indentation
    printf("Hello" "Who says so?"
    "Hark to the sound of dreams."
       "That's great \n"
    );
    printf("How are you \);
}

/ / the result
// How are you? Listen, the sound of dreams is so good
/ / how are you
Copy the code
#include<stdio.h>
int main(void){
    // A string is a null-terminated array of char, so the array-pointer relationship applies here
    char a[] = {'a'.'b'.'c'.'\ 0'};
    // Note that c is a constant and the element in c is a variable and b is a variable
    char *b  = "abc";  // A pointer to the address of a string constant
    char c[] = "abc";  // Each element of the array is initialized to the corresponding character of the string constant, and the literal is stored in static memory. The array is created at run time
    printf("%s %p\n",a,a);
    printf("%s %p\n",b,b);
    printf("%s %p\n",c,c);
    printf("%s %p\n"."abc"."abc");
    // String array and pointer
    char d[][8] = {"It is 1"."This is 2"."This is a 3"};  // Array of characters
    char *e[8] = {"It is 1"."This is 2"."This is a 3"};  // Array of Pointers, where each pointer points to a corresponding string literal
    // The following is very easy to error, can not be pure ** because such an object is 1 byte char, pointer ++ how? Compilation is going to be a problem. Then you must also make it clear that this is an array pointer!
    char (*f)[8] = (char[] [8]) {"It is 1"."This is 2"."This is a 3"};  // Must be an array pointer to a string array compound literal
    printf("%s %s %s %p %p\n",d[0],d[1],d[2],d,d[1]);
    printf("%s %s %s %p %p\n",e[0],e[1],e[2],e,e[1]);
    printf("%p\n"."This is 2");
    printf("%s %s %s %p %p\n",f[0],f[1],f[2],f,f[1]);  // Compound literals as a whole
}
/ / the result
// abc 0x7ffee536d5e4
// abc 0x10a892f62
// abc 0x7ffee536d5d4
// abc 0x10a892f62
// This is 1 this is 2 this is 3 0x7ffee536d640 0x7ffee536d648
// This is 1 this is 2 this is 3 0x7ffee536d600 0x10A892f75
// 0x10a892f75
// This is 1 this is 2 this is 3 0x7ffee536d5e8 0x7ffee536d5f0

Copy the code
#include<stdio.h>
#include<string.h>
int main(void){
    // String and const pointer
    // char a[] = "test ";
    char a[] = "abc";
    const char *p =  a; // The array name represents the address of the first element of the array
    // printf("%lu",strlen(a)); // For the "test", the result is 6, so if you want to output a single Chinese character, you should create a two-dimensional array, since one Chinese character corresponds to two chArs
    printf("%c",*p); // Normal output a
    *p = '0';
}

/ / the result
// test.c:10:8: error: read-only variable is not assignable
// *p = '0';
/ / ~ ~ ^
// 1 error generated.
Copy the code
  1. Store multiple different strings: pointer representation and array representation

See the string array and pointer above:

char d[][8] = {"It is 1"."This is 2"."This is a 3"};  // Array of characters
char *e[8] = {"It is 1"."This is 2"."This is a 3"};  // Array of Pointers, where each pointer points to a corresponding string literal
    // The following is very easy to error, can not be pure ** because such an object is 1 byte char, pointer ++ how? Compilation is going to be a problem. Then you must also make it clear that this is an array pointer!
char (*f)[8] = (char[] [8]) {"It is 1"."This is 2"."This is a 3"};  // Must be an array pointer to a string array compound literal
Copy the code
  1. Gets, fgets, fputs, puts, gets_s, putchar, getchar, scanf, printf comparison
char * gets(char *)
char * fgets(char *__restrict__, int, FILE *)
int fputs(const char *__restrict__, FILE *__restrict__)
int	 getchar(void);
int	 scanf(const char * __restrict, ...) __scanflike(1.2);
Copy the code
  • getsDeprecated by C11 (compiler will have itwarning: this program uses gets(), which is unsafe.).getsIt’s reading a line of data, and it doesn’t matter if you don’t have enough space, and then you write it down, and that’s a security issue, it’s undefined. The correspondingputsPrint the string and end it with”\n“,getsIs a directdiscarded\n“(does not put back the input buffer).
  • fgetsOften used insteadgetsThe first parameter is a pointer to the storage location, the second parameter is the maximum number of characters read, and the third parameter is the location from which the file is readBuffer overflowThe problem. The correspondingfputsPrint the string withputsThe difference is that it doesn’t print much more.”\n“, sofgetsWill directly put”\n“Store it in a character array instead of throwing it awayfputsYou also need to specify a second parameter file (if it’s a screen)stdout). It returns a null pointer at the end of the file:NULL.
  • gets_sIs an optional extension, new in C11, that the compiler doesn’t necessarily implement, it limits the number of characters that can be read with one argument, it only reads from standard input, so it only has two arguments, and the newline character is discarded, and then the newline is discarded, and the handler is required.
  • getcharIs a single character reading function that returns a character and takes no arguments. The correspondingputcharPrints a single character to the screen. It reads at the end of the file and returns:EOF, its value is- 1Defined in thestdio.hIn the.
  • scanfVery versatile input function that reads words and has format specifiers for strings.”\s“, but only one word, it separates the words with whitespace, and subsequent characters are not discarded directly back into the buffer. andgetsAgain, overflow will resultabortAbort, so be careful to allocate enough space. We’ve already looked at the problem of input/output buffers, which C takes as inputThe bufferThe strategy of keyboard input isLine buffered inputThe buffer is flushed only after you press ENTER, so you can change it if you make a mistake. It reads at the end of the file and returns:EOF, its value is- 1Defined in thestdio.hIn the.
#include<stdio.h>
#define MAXSIZE 10
int main(void){
    char a[MAXSIZE];
    char b;
    / / the fgets function
    fgets(a,MAXSIZE,stdin);
    fputs(a,stdout);
    b = getchar();
    putchar(b);
}

/ / the result
// hello,it's me,do you know?
// hello,it's% 
Copy the code
  1. NULL characters, whitespace, EOF, NULL pointer NULL
  • Null characterC uses it to mark the end of a string:\ 0, its ASCII code value is (equivalent to)0But instead of the number zero, it isNon-print character. The string in C must end with it.
  • Whitespace: In ASCII encoding, such whitespace includes space ‘ ‘, horizontal TAB ‘\t’, newline ‘\n’, vertical TAB ‘\v’, feed ‘\f’, and carriage return ‘\r’.
  • EOF: define thestdio.h, its value is- 1forgetchar,scanfReturns when a function that returns a number reads the file at the end of the file. Why is it- 1? becausegetcharThe return value is usually between 0-127, or 0-255 if the system supports extended character sets, in either case- 1Does not correspond to any character.
  • Null pointer: NULL, used forfputsAnd so on when a function that needs to return a char pointer reads the end of the file. Take MAC as an example, is defined as#define __DARWIN_NULL ((void *)0), it is avoidPointer to type0, can be replaced by the number 0,NULLDefined in the_null.h,__DARWIN_NULLDefined in the_types.hFile. This pointer is guaranteed not to point to valid data.
  1. String functions: strlen, strcat, strncat, STRCMP, STRNCMP, strcpy, strncpy, sprintf, STRCHR, STRRCHR, STRPBRK, STRSTR
size_t	 strlen(const char *__s)
char *strcat(char *s1, const char *s2)
char *strncat(char *s1, const char *s2, size_t n)
int	 strcmp(const char *__s1, const char *__s2)
int	 strncmp(const char *__s1, const char *__s2, size_t __n)
char *strcpy(char *dst, const char *src)
char *strncpy(char *dst, const char *src, size_t n)
sprintf(str, __VA_ARGS__)
const char* strchr(const char* __s, int __c)
const char* strrchr(const char* __s, int __c)
const char* strpbrk(const char* __s1, const char* __s2)
const char* strstr(const char* __s1, const char* __s2)
Copy the code
char * strpbrk(const char * cs,const char * ct)
{
    const char *sc1,*sc2;
    for( sc1 = cs; *sc1 ! ='\ 0'; ++sc1)
    {
        for( sc2 = ct; *sc2 ! ='\ 0'; ++sc2)
        {
            if (*sc1 == *sc2)
            {
                return (char*) sc1; }}}return NULL;
}
Copy the code
#include<stdio.h>
#include<string.h>
#define MAXSIZE 100
int main(void){
    char a[MAXSIZE] = "testA";
    char b[] = "testB";
    // strlen Specifies the length of the string, excluding null characters
    printf("1: %zd\n".strlen(b));
    // strcat string connection. Note that dest space is sufficient, otherwise abort is invoked
    printf("2: %s %s\n".strcat(a,b),strcat(a,b)); // Note that the function is called before printing, so both end up with the same result
    // strncat string with maximum length concatenation (to prevent overflow)
    printf("3: %s\n".strncat(a,"hello".3));  // testAtestBtestBhel
    // STRCMP string by ASCII value, first -1(or small -1), equal 0, last 1(or large 1)
    printf("4: %d\n".strcmp(a,b));  //-1, note that the comparison is a string, not a character
    // Compare the first n characters of STRNCMP to upgrade STRCMP
    printf("5: %d\n".strncmp(a,b,1));  You can also use string constants to see if a string starts at the specified beginning
    // strcpy string copy, equivalent to "assign"
    strcpy(a+1,b);  // The result of printing it directly is still testB, because the function returns the address of the first argument
    printf("6: %s\n",a);  //ttestB
    // strncpy string with maximum length copy (to prevent overflow)
    strncpy(a,b+1.2);  // Print its result esestB directly, not desired, because it exceeds 2, resulting in no '\0' character copied to b!
    a[2] ='\ 0'; // Null characters need to be set manually
    printf("7: %s\n",a);  //es
    // sprintf prints to a string (equivalent to rewriting copy), declared in stdio.h, with dest as the first argument and the rest as printf
    sprintf(a,"nihao %s " "hello",b);  //nihao testB hello, be careful not to form your own print to yourself, unexpected results will appear
    printf("8: %s\n",a);  //es nihao testB hello
    // STRCHR returns a pointer to the position of the first character found
    printf("9: %s\n".strchr(a,'s'));  //stB hello
    STRRCHR returns a pointer to the position of the last character found
    printf("10: %s\n".strrchr(a,'l'));  //lo
    // STRPBRK finds the position that first contains any character in the search string and returns it
    printf("11: %s\n".strpbrk(a,"abc")); //ao testB hello
    // STRSTR searches for the string, returns the first address of the string found first, returns a null pointer if not found
    printf("12: %s\n".strstr(a,"test"));  // testB hello
}   

/ / the result
// 1: 5
// 2: testAtestBtestB testAtestBtestB
// 3: testAtestBtestBhel
/ / 4:1
// 5: 0
// 6: ttestB
// 7: es
// 8: nihao testB hello
// 9: stB hello
// 10: lo
// 11: ao testB hello
// 12: testB hello
Copy the code
  1. Ctype. h Character-specific functions

See ctype.h for ctype.h

// Return both int and non-zero (true), zero (false)

isalnum(int _c)  // If c is the numbers 0-9 or the letters A-z and a-z, return non-zero, otherwise return zero
isalpha(int _c)  // If it is an English letter, return non-0 (lowercase 2, uppercase 1). If it is not a letter, return 0.

/* isblank() refers to a blank character used to separate words in a line of text, not to break lines or pages, or to have other special effects. Isspace () has no such requirements and refers to all whitespace characters. That is, the whitespace referred to by isblank() is a subset of isspace(). * /
isblank(int _c)  // Check whitespace: '\t' and '' (Spaces)
isspace(int _c)  // Check for all whitespace characters

islower(int _c)  // Check if a character is lowercase
isupper(int _c)  // Check if a character is uppercase

isprint(int _c)  // Check if a Character is Printable Character
iscntrl(int _c) // Checks if a Character is a Control Character, as opposed to a printable Character.

isdigit(int _c)  // Checks if a character is a decimal number
isxdigit(int _c) // Checks if a character is a hexadecimal number

ispunct(int _c)   // Check if a character is punctuation

// If the conversion succeeds, return the letter corresponding to _c; If the conversion fails, return _c (value unchanged).
tolower ( int _c )  // Convert uppercase characters to lowercase characters
toupper(int _c)  // Convert lowercase letters to uppercase letters
Copy the code
#include<stdio.h>
#include<ctype.h>
int main(void){
    // ctype character handler function
    printf("isalnum: %d\n".isalnum('1'));  / / 1
    printf("isalpha: %d\n".isalpha('1'));  / / 0

    printf("isdigit: %d\n".isdigit('1'));  / / 1
    printf("isxdigit: %d\n".isxdigit('1'));  / / 1

    printf("isprint: %d\n".isprint('1'));  / / 1
    printf("iscntrl: %d\n".iscntrl('1'));  / / 0

    printf("isupper: %d\n".isupper('a'));  / / 0
    printf("islower: %d\n".islower('a'));  / / 1

    printf("isblank: %d\n",isblank('\n'));  / / 0
    printf("isspace: %d\n".isspace('\n'));  / / 1
}   

/ / the result
// isalnum: 1
// isalpha: 0
// isdigit: 1
// isxdigit: 1
// isprint: 1
// iscntrl: 0
// isupper: 0
// islower: 1
// isblank: 0
// isspace: 1
Copy the code
  1. Command line arguments, if the argument is an integer, how to convert?

You can pass two arguments in the main function. The first is the number of strings in the command line, int argc, The other is a list of all the strings on the command line char * argv[] (the system uses Spaces to indicate the end of one string and the end of the next).

To convert strings to numeric data, use the function declared in stdlib.h:

// Returns the converted value
double	 atof(const char *);  // Convert the string to a double value
int	 atoi(const char *);  // Convert a string to an integer value
long	 atol(const char *);  // Convert the string to a long integer
long long    atoll(const char *);  // Convert the string to a long integer

// The first argument is the address of the string to be converted. The second argument is the address of a pointer that identifies the address of the input digit ending character. Base indicates what base to write in.
double	 strtod(const char *, char* *) __DARWIN_ALIAS(strtod);
float	 strtof(const char *, char* *) __DARWIN_ALIAS(strtof);
long	 strtol(const char *__str, char **__endptr, int __base);
long double
	 strtold(const char *, char* *);
#if! __DARWIN_NO_LONG_LONG
long long 
	 strtoll(const char *__str, char **__endptr, int __base);
#endif / *! __DARWIN_NO_LONG_LONG */
unsigned long
	 strtoul(const char *__str, char **__endptr, int __base);
#if! __DARWIN_NO_LONG_LONG
unsigned long long
	 strtoull(const char *__str, char **__endptr, int __base);
Copy the code

Ato does not have error detection, and the results of illegal actions are undefined, whereas STRTO does have error detection, so using STRTO is safer.

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char * argv[]){
    char * end;
    printf("Total number of strings: %d\n",argc);  
    Argv [0] is the command, argv[1] is the first argument, and so on
    printf("First input integer: %d\n",atoi(argv[1]) +1);
    printf("Double precision float for second input: %f\n",atof(argv[2]) +1.0 f);
    printf("Third input double: %f\n",strtod(argv[3],&end)+1);
    printf("Fourth input single precision float: %f\n",strtof(argv[4],&end)+1.0);
}   

// Result example
//./test 1 1.55 1.55 1.55
// Total number of strings: 5
// The first input integer: 2
// The second input is a double precision float: 2.550000
// The third input is a double-precision floating point number: 2.550000
// The fourth input is a single-precision floating point number: 2.550000
Copy the code