strcat()函數

函數原型 extern char *strcat(char *dest, count char *src)

頭文件:在c語言中 <string.h>  在c++中,則存在於<cstring>

功能:接收兩個字符串作爲參數。把函數把第二個字符串符備份附加在第一個字符串的末尾,並把拼接後形成的新字符串作爲第一個字符串,第二個字符串不變。 

缺點:strcat()函數無法檢查第一個數組是否能容納第二個字符串,如果分配給第一個數組的空間不夠大,多出來的字符溢出到相鄰存儲單元時就會出問題。

#include <stdio.h>
#include <string.h>
#define SIZE 80
char *s_gets(char *st, int n);

int mian(void)
{
    char flower[SIZE];    //定義第一個數組
    char addon[] = "This is an array";    //定義第二個數組
    
    puts("what is your favorite?");   //提示信息
    if(s_gets(flower,SIZE));        //接收一個字符串,給flower數組賦值。
    {
        strcat(flower, addon);    //拼接字符串
        puts(flower);             //輸出第一個字符串
        puts(addon);              //輸出第二個字符串
    }
    else
    {
        puts("End of file encountered!");   //提示信息,遇到文件結束
    }
    puts("bye");

    return 0;    
}
//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;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章