返回首页
EN
H7 / SECURITY RESEARCH NOTES

2021.11.8

字符串和字符串函数

conception: 字符串是以空字符(\0)结尾的char类型数组。

程序中定义字符串

// Two solutions
// 1.pointer define
const char *pt = "this is a string";
// 2.array define
char arr[] = "this is a string"; 
char arr[20] = "this is a string";

// Following is the distinction of two solution:
// the first solution: pointer point original string in the static memory
// the first solution: pointer can't change value of the string
// the second solution: the array is the copy from original string in the static memory
// the second solution: value of array can be changed

字符串输入与输出

// common input and output function
// gets() is deprecated
char words[10];
gets(words); // Read 9 character and add a new line character

// puts()
puts("hello, world!"); // Print string and add a new line character

// fgets()
#define STLEN 10
char words[STLEN];
fgets(words, STLEN, stdin); // stdin means you want to accept input from keyboard
// fgets will read new line symbol as a character

// fputs()
fputs(words, stdout); // stdout means you want to output on the screen, it will not add a new line character

// gets_s()
#define STLEN 10
char words[STLEN];
gets_s(words, STLEN); // gets_s() only read data from stdin, it will not accept new line symbol like fgets()

// scanf()

// printf()
  • Following is encapsulation of fgets()
char * s_gets(char * st, int n)
{
    char * ret_val;
    int i = 0;

    ret_val = fgets(st, n, stdin);
    if (ret_val)
    {
        while (st[i] != '\n' && st[i] != '\0')
            i++;
        if (st[i] == '\n')
            st[i] = '\0';
        else         
            while (getchar() != '\n')
                continue;
    }
    
    return ret_val;
}