strcat函数是一个字符串拼接函数,能够将第二个字符串备份到第一个字符串末尾,并且自己本身不改变,只改变第一个字符串。
strcat函数的类型是 char *(即,指向 char 的指针)。strcat()函数返回第一个参数,即拼接第二个字符串后的第一个字符串的地址。
下面是具体代码
#include<stdio.h>
#include<string.h>
#define SIZE 80
char * s_gets(char * st, int n);
int main(void)
{
char flower [SIZE];
char addon [] = "s smell like old shoes.";
puts("What's your favorite flower?");
if(s_gets(flower, SIZE))
{
strcat(flower, addon);
puts(flower);
puts(addon);
}
else
puts("End of file encountered!");
puts("Bye");
return 0;
}
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;
}
以上就是strcat具体代码
这里strcat函数中的循环尤为重要,循环第一行使用 while()循环对输入字符串是否有回车和空格进行检查,并使用 if()将其替换成 空格,并且使用 else 重新对 字符串进行检查,continue 返回到else的while中,到字符串末尾结束循环,并且返回该字符串,使之进入strcat函数,与字符串addon进行拼接。