-
A string is terminated by the null character
\0and is an array of thechartype. -
The
puts()function displays only strings and automatically adds a newline character to the end of the displayed string.
Initializing an array copies the string from static storage into the array, while initializing a pointer copies only the string's address to the pointer ---- I do not quite understand this yet, so I will leave it as something to revisit
String Input
- 读取字符串时首先第一步是为需要读取的字符串分配足够的内存空间;分配内存空间后,便可读取字符串,c语言提供许多读取字符串的函数:
scanf()、gets()、fgets().
- gets()
读取整行输入,直到遇到换行符,然后丢弃换行符,存储其余字符,并且在这些字符末尾添加一个空字符使其成为字符串。
# 注:gets()在c11标准开始废除了,因为其不会检查读取字符串的大小,是一个不安全的函数。
- scanf()
以第一个非空白字符作为字符串的开始。如果使用%s作为转换说明,以下一个空白字符(空行、空格、制表符或换行符)作为字符串的结束(字符串不包括空白字符)。如果制定了字段宽度,如%10s,那么scanf()将读取10个字符或读到第一个空白字符停止。
该函数返回一个整数值,该值等于scanf()成功读取的项数或EOF(读到文件结尾的时候返回EOF)
- fgets()
第二个参数指明读入字符的最大数量,如果为n,则将读入n-1个字符,或者读到第一个换行符为止;
fgets()读到第一个换行符,会把它存储在字符串中。
fgets()第三个参数指明要读入的文件。如果读入从键盘输入的数据,则以stdin作为参数。
fgets()返回指向char的指针,该函数返回的地址与传入的第一个参数相同。
fgets()读到文件末尾会返回"空指针(null pointer)",在C语言中用NULL来代替比较常见,如果读入数据时出现某些错误,也返回NULL。
- s_gets()函数=>该函数为自己创建:读取整行输入并使用空字符代替换行符,或者读取一部分输入(这部分输入是规定大小的)并丢弃其余部分。
char * s_gets(char * st, int n)
{
char * ret_val;
int i;
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;
}
- scanf_s()
# Reference Link
1.https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/scanf-s-scanf-s-l-wscanf-s-wscanf-s-l?redirectedfrom=MSDN&view=msvc-170 # Define of microsoft official
2.https://stackoverflow.com/questions/22024213/calling-scanf-s-with-array-of-chars # Introduce how to handle array of characters with scanf_s()
3.https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/countof-macro?view=msvc-170 # Introduce _countof()
# Summary
unlike scanf() function, scanf_s() require you to specify buffer size for some parameters.
specify the sizes for all %c,%C,%s,%S.The buffer size in character is passed as an additional parameter.
The most important is it immediately follows the pointer to the buffer or variable.
String Output
- puts()
把字符串的地址作为参数传给它即可输出,从地址开始到遇到空字符结束,该函数会在输出的末尾添加一个换行符。
- fputs()
第2个参数指明要写入数据的文件,如果是显示屏,则为stdout。
与puts()不同,fputs()不会在输出的末尾添加换行符。
- printf()
printf()不会在字符串末尾添加换行符。
String Functions
- strlen()
计算字符串长度,但是其不会包含字符串末尾的空字符'\0'。
- strcat() # 不过现在已经弃用了,都用strncat_s()函数了
接受两个字符串作为参数,并将第2个字符串的备份附加在第1个字符串的末尾,并把拼接后形成的新字符串作为第1个字符串,第2个字符串保持不变。
strcat()返回第1个参数,即拼接第2个字符串后的第1个字符串的地址。
用法如下图:

- strcmp()
https://www.cplusplus.com/reference/cstring/strcmp/
Command-Line Arguments
-
The
Ccompiler allowsmain()to have no parameters or two parameters (some implementations allowmain()to have more parameters, as an extension to the standard). -
When
main()has two parameters, parameter1is the number of strings on the command line. -
char** argvis equivalent tochar * argv[], becauseargvis a pointer to a pointer.