c语言字符串处理相关函数

字符串输入函数:

1. fgets:遇到’\n‘或者EOF停止读取,读取结果中包含'\n'。

char *fgets(char *s, int size, FILE *stream);

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.

 

2. gets:遇到’\n‘或者EOF停止读取,读取结果中不包含'\n'。

char *gets(char *s);

gets() reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF, which it replaces with a null byte ('\0'). No check for buffer overrun is performed (see BUGS below).

 

3. scanf("%s"):返回第一个连续非空字符组成的字符串,读取结果中不包含'\n'以及空白字符。

比如用户输入为"        abc.def&gh^#&*$%$#%*(123   sad  "的话,

则读取结果为"abc.def&gh^#&*$%$#%*(123"。

Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

总结:若输入由多个连续非空字符序列组成,且这些连续非空字符序列之间含有空格字符,则scanf不能处理,而fgets和gets能处理。

 

字符串输出函数:

1. int fputs(const char *s, FILE *stream); 不会额外输出'\n'.

fputs() writes the string s to stream, without its terminating null byte ('\0').

 

2. int puts(const char *s); 会额外输出'\n'.

puts() writes the string s and a trailing newline to stdout.

 

3. printf("%s"):不会额外输出'\n'.

 

字符串长度测试函数:

size_t strlen(const char *s);  除'\0'以外的其他所有字符的个数。

The strlen() function calculates the length of the string s, excluding the terminating null byte ('\0').

 

测试代码: 

#include <stdio.h>

#define MAXLINE 100

void print(char buf[])
{
    int i = 0;
    for(;i < MAXLINE;i++)
        printf("%c",buf[i] == '\0'? '#' : (buf[i] == '\n'? '@':buf[i])); //便于观察
    printf("\n");
}

int main()
{
    char fgetsbuf[MAXLINE] = {0};
    char getsbuf[MAXLINE] = {0};
    char scanfbuf[MAXLINE] = {0};
    
    if(fgets(fgetsbuf,sizeof(fgetsbuf),stdin) == NULL)
        perror("fgets");
    print(fgetsbuf);

    if(gets(getsbuf) == NULL)
        perror("gets");
    print(getsbuf);

    scanf("%s",scanfbuf);
    print(scanfbuf);

    printf("----output function test----\n");
    fputs(getsbuf,stdout);
    printf("|");
    puts(getsbuf);
    printf("|");
    return 0;
}

 

 

运行结果:

tsiangleo@leo-ThinkPad-Edge:~/ss$ ./a.out 
     abc def         gh
     abc def        gh@######################################################################################
     abc def        gh
     abc def        gh#######################################################################################
     abc def        gh
abc#################################################################################################
----output function test----
     abc def        gh|     abc def        gh
|tsiangleo@leo-ThinkPad-Edge:~/ss$ 

 

你可能感兴趣的:(c语言字符串处理相关函数)